“HTML背景图片”的版本间差异
(创建页面,内容为“20 几乎可以为任何 HTML 元素指定背景图像。 == HTML 元素上的背景图片 == 要在 HTML 元素上添加背景图像,请使用 HTML''' style '''属性和 CSS''' background-image '''属性: <sample title="" desc="Add a background image on a HTML element:" > <p style="background-image: url('img_girl.jpg');"> </sample> 您还可以在''' <style> ''' 元素中指定背景图像,在以下''' <head> '''…”) |
无编辑摘要 |
||
第6行: | 第6行: | ||
== HTML 元素上的背景图片 == | == HTML 元素上的背景图片 == | ||
要在 HTML 元素上添加背景图像,请使用 HTML''' style '''属性和 CSS''' background-image '''属性: | 要在 HTML 元素上添加背景图像,请使用 HTML''' style '''属性和 CSS''' background-image '''属性: | ||
第15行: | 第16行: | ||
您还可以在''' <style> ''' | 您还可以在''' <nowiki><style></nowiki> ''' | ||
元素中指定背景图像,在以下''' <head> ''' | 元素中指定背景图像,在以下''' <nowiki><head></nowiki> ''' | ||
部分: | 部分: | ||
2022年8月4日 (四) 17:06的版本
几乎可以为任何 HTML 元素指定背景图像。
HTML 元素上的背景图片
要在 HTML 元素上添加背景图像,请使用 HTML style 属性和 CSS background-image 属性:
示例
Add a background image on a HTML element:
<p style="background-image: url('img_girl.jpg');">
您还可以在 <style> 元素中指定背景图像,在以下 <head> 部分:
示例
Specify the background image in the '''
'''
element:" >
<style>p { background-image: url('img_girl.jpg');
}</style>
页面上的背景图片
If you want the entire page to have a background image, you must specify the background image on the <body> element:
示例
Add a background image for the entire page:
<style>body { background-image: url('img_girl.jpg');
}</style>
Background Repeat
If the background image is smaller than the element, the image will repeat itself, horizontally and vertically, until it reaches the end of the element:
示例
<style>body { background-image: url('example_img_girl.jpg');}</style>
To avoid the background image from repeating itself, set the background-repeat property to no-repeat .
示例
<style>body { background-image: url('example_img_girl.jpg');
background-repeat: no-repeat;}</style>
Background Cover
If you want the background image to cover the entire element, you can set the background-size property to cover. Also, to make sure the entire element is always covered, set the background-attachment property to fixed: This way, the background image will cover the entire element, with no stretching (the image will keep its original proportions):
示例
<style>body { background-image: url('img_girl.jpg');
background-repeat: no-repeat; background-attachment: fixed;
background-size: cover;
}</style>
Background Stretch
如果您希望背景图像拉伸以适合整个元素,您可以将 background-size 属性设置为 100% 100% :
尝试调整浏览器窗口的大小,您会看到图像会拉伸,但始终会覆盖整个元素。
示例
<style>body { background-image: url('img_girl.jpg');
background-repeat: no-repeat; background-attachment: fixed;
background-size: 100% 100%;
}</style>
了解更多 CSS
从上面的示例中,您了解到可以使用 CSS 背景属性来设置背景图像的样式。 要了解有关 CSS 背景属性的更多信息,请学习我们的CSS 背景教程。