在本文中,我们将添加一张图片作为网页的背景图片。背景图像用于使网站更具互动性和吸引力。它可以应用于许多样式。
方法:
- 在 body 标签中,通过传递图片的 URL 或位置路径在 background 属性中指定背景图片。
- 添加 CSS 样式属性。
句法:
Website Body
示例 1:在本示例中,我们将使用上述方法添加背景图像。
HTML
Website
GeeksforGeeks
Background Image
HTML
Website
GeeksforGeeks
Background Image
HTML
Website
GeeksforGeeks
Background Image
HTML
Website
GeeksforGeeks
Background Image
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_add_an_image_as_background_image_of_a_web_page_?_0.jpg)
图 1
示例 2:在此示例中,我们将使用 background-image 属性在 CSS 代码中指定图像的 URL 或路径。
句法:
注意:我们也可以在 style 标签下添加 CSS 代码,或者我们可以创建单独的文件。
HTML
Website
GeeksforGeeks
Background Image
注意:我们将获得与示例 1 中相同的输出。
现在我们将了解如何使用 CSS 属性为背景图像设置样式。
1. Background-repeat: background-repeat 属性用于添加或删除背景图像在任何方向的重复。
句法:
background-repeat: no-repeat;
例子:
HTML
Website
GeeksforGeeks
Background Image
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_add_an_image_as_background_image_of_a_web_page_?_1.jpg)
图 2
2.背景附件和大小:背景附件属性用于指定背景图像相对于其容器的附件类型。 background-size 属性用于设置背景图像的大小。
句法:
background-attachment: fixed;
background-size: cover;
示例:我们指定此修复,因为我们不希望背景图像随页面滚动。我们将 background-size 设置为 100% 的高度和 100% 的宽度以覆盖整个屏幕。
HTML
Website
GeeksforGeeks
Background Image
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_add_an_image_as_background_image_of_a_web_page_?_2.jpg)
图 3