这节课,咱们学习下背景色与背景图片的玩法。先用上一节学习的知识,设置一个宽和高。
<html>
<head>
<meta charset="utf-8">
<!-- ... -->
<style>
div {
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
背景色
背景色
的用法,非常简单。好了,没了。。。这就是背景色
课程的全部内容。
<style>
div {
/* ... */
background-color: #1f99b0;
}
</style>

背景图
还是来看看背景图是怎么玩的吧。先到ITFun.tv上,找到CSS入门
课程的图片,右键另存到和index.html
同目录的位置。千万不好搞错位置了,不然图片会找不到的。接着将文件名,改为css.jpg
。
去掉背景色
,添加上边框
和背景图片
。
<style>
div {
width: 600px;
height: 600px;
border: 1px solid;
background-image: url("css.jpg");
}
</style>
刷新一下,发现背景图片果然能显示了。但是由于我们图片比较小,所以在这个div
里,自动的重复了出来。

背景图重复
我们尝试设置下背景图重复相关的属性。
<style>
div {
/* ... */
background-repeat: repeat-x;
}
</style>

刷新下,现在只有横向被重复了。这里的x
的意思是在x轴
,也就是横向重复
。与此相对的,当然还有个repeat-y
,这就是纵向重复
了。
如果你想让它不重复,当然也有办法的。你需要使用no-repeat
,这就是不重复
了。
背景图位置
关于图片的位置,还可以进一步调整。
<style>
div {
/* ... */
background-repeat: no-repeat;
background-position: top right;
/*background-position: bottom right;*/
/*background-position: center;*/
/*background-position: 100px 300px;*/
}
</style>

其实这个属性,也是可以缩写在一行的,平常我们经常也这么干。
<style>
div {
/* ... */
background: url("css.jpg") no-repeat center;
}
</style>
背景图大小
现在图片比较小,虽然居中了,可是看着还是很奇怪。能不能让图片覆盖整个div
的大小呢?
<style>
div {
/* ... */
background-size: contain;
}
</style>
顾名思义,background-size
就是背景图的大小了。contain
意思是,等比例的占满整个div
。这样做完后,发现上下两边还是有空白。

我们将属性值改为cover
,它的意思是完全覆盖背景区域
。刷新,发现现在图片占满了整个div
了,但是图片的左右两边,有些地方看不见了。
<style>
div {
/* ... */
background-size: cover;
}
</style>

这些做法,都是为了保持图片等比例缩放,不会变形的常用的设置。如果你说,我不管是否会变形,只要把图片完整的丢在div
里面,占满整个框,那也不是不可以。
<style>
div {
/* ... */
background-size: 100% 100%;
}
</style>

background-size
也是可以缩写到background
的,但是注意下,需要先加上一个 /
<style>
div {
/* ... */
background: url("css.jpg") no-repeat center / cover;
}
</style>
总结
属性名 |
用法举例 |
意义 |
background-color |
#1f99b0 |
背景色 |
background-image |
url("css.jpg") |
背景图片地址 |
background-repeat |
no-repeat、repeat-x、repeat-y |
背景图重复 |
background-position |
center |
背景图片位置 |
background-size |
cover、contain |
背景图大小 |
background |
url(html.jpg) no-repeat center / cover |
同时设置背景的多个属性 |