背景颜色
背景色
background-color为元素设置背景色,通常属性值为颜色名称或颜色编码。
因为HTML文档中body元素包含了HTML文档的所有内容,所以如果要改变整个页面的背景颜色,只需要设置body元素的background-color属性。
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<style type="text/css">
body {
background-color: lightyellow;
}
h1 {
color: gray;
background-color: palegreen;
}
p {
background-color: lightgray;
}
</style>
</head>
<body>
<div>
<h1>CSS让网页样式更丰富</h1>
<p>这是一个段落</p>
</div>
</body>
</html>
效果如下:
背景图片
背景图片
使用background-image属性设置元素的背景属性,常见的网页背景图就是这样设置的。其中,属性值通过url指定图片链接。
书写格式:
background-image: url("图片链接")
例如:
<head>
<meta charset="utf-8">
<title>Hello World</title>
<style type="text/css">
body {
/*设置背景图片*/
background-image: url("./Assert/memphis-colorful.png")
}
div {
width:90%;
height: 100%;
margin: auto;
background-color: #FCFDF8;
}
</style>
</head>
平铺背景图像
指定了背景图像之后,默认背景图是平铺重复显示。如果想要设置图像在水平方向、垂直方向平铺或其他方式,可以设置background-repeat属性。
- 默认平铺
body {
/*设置背景图片*/
background-image:url("./Assert/sun.jpg");
}
- repeat-x
body {
/*设置背景图片*/
background-image:url("./Assert/sun.jpg");
background-repeat: repeat-x;
}
3. repeat-y
body {
/*设置背景图片*/
background-image:url("./Assert/sun.jpg");
background-repeat: repeat-y;
}
4. no-repeat
body {
/*设置背景图片*/
background-image:url("./Assert/sun.jpg");
background-repeat: no-repeat;
}
背景定位与背景关联
背景定位
background-position属性改变图像在背景中的位置:
body {
/*设置背景图片*/
background-image: url("https://www.educoder.net/attachments/download/211104");
background-repeat: no-repeat;
background-position: right top;
}
背景关联
当页面较长时,滚动页面,背景图像也会随之滚动。当文档滚动到超过图像的位置时,图像就会消失。如果想要背景图像不随页面滚动而改变位置。可以使用background-attachment属性,将其值设置为fixed。
body {
background-image: url("https://www.educoder.net/attachments/download/211104");
background-repeat: no-repeat;
background-attachment: fixed;
}
简写背景
多种背景属性的设置,为了简化这些属性的书写,我们可以将这些属性合并在同一个属性中。
body {
background:#ffffff url("./Assert/sun.jpg") no-repeat right top;
}