HTML 允许我们为 div、span、table 等元素或整个页面设置背景图像。
如何设置背景图片?
您可以使用 CSS 属性为任何 HTML 元素设置背景图像。此外,您还可以使用 HTML background 属性来设置 HTML 元素或整个页面的背景。该属性已弃用,建议使用 CSS 样式表进行背景设置。以下是将背景图像 background-image 与任何 HTML 标签一起使用的语法。
在 HTML 中:在 CSS 中:
<tag background="URL/of/image">
tag {
background-image: url('URL/of/image"');
background-repeat: no-repeat;
}
例
以下示例演示如何为网页设置背景图像。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div{
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
}
</style>
</head>
<body background="/html/images/logo.png">
<div>
<h1>Welcome to My Website</h1>
<p>
This is an example of setting a
background image using HTML
attributes.
</p>
</div>
</body>
</html>
Background Repeat 属性
有时我们为元素设置的背景图像不够大,无法覆盖元素的所有区域。在这种情况下,图像将在水平和垂直方向上重复,直到到达元素的末尾。为避免重复背景图像,您可以将 background-repeat 属性设置为 no-repeat
例以下示例显示了如何使用背景图像 repeat 属性。这解释了如何在 HTML 中使用 repeat、repeat-x 和 repeat-y 属性。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Background Repeat Example</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
div {
width: 600px;
height: 200px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
background-image: url('/html/images/logo.png');
}
.repeat-x {
background-repeat: repeat-x;
}
.repeat-y {
background-repeat: repeat-y;
}
.repeat {
background-repeat: repeat;
}
</style>
</head>
<body>
<h2>Repeat-X</h2>
<div class="repeat-x">
</div>
<h2>Repeat-Y</h2>
<div class="repeat-y">
</div>
<h2>Repeat</h2>
<div class="repeat">
</div>
</body>
</html>
背景封面
如果希望背景图像覆盖整个元素,可以将 background-size 属性设置为 cover。通过设置此设置,背景图像将覆盖所有元素部分而不会拉伸它。
例以下示例演示如何在整个元素区域中覆盖图像。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.background-cover {
background-image: url('/html/images/logo.png');
/* Cover the entire container */
background-size: cover;
/* Center the image */
background-position: center;
background-repeat: no-repeat;
width: 100%;
height: 150px;
color: white;
text-shadow: 1px 1px 2px black;
border: 2px solid #ccc;
}
</style>
</head>
<body>
<div class="background-cover">
<h1>Welcome to My Website</h1>
</div>
</body>
</html>
Background Stretch 属性
通过将 background-size 属性设置为 100%,您可以拉伸图像以适合元素。
例以下示例演示如何使用 stretch 属性。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
height: 100vh;
}
.background-stretch {
background-image: url('/html/images/logo.png');
/* Stretch the image to cover Div */
background-size: 100% 100%;
width: 80%;
height: 80%;
border: 2px solid;
}
</style>
</head>
<body>
<div class="background-stretch">
</div>
</body>
</html>