我正在尝试将背景图像添加到div,但它不起作用,你能帮帮我吗!
html body {
height: 100%;
}
.front-page {
display: 100%;
width: 100%;
padding: 0;
border: 0;
background: url("classroom.jpg") no-repeat center cover;
}
<body>
<div class="front-page">
</div>
</body>
三个问题:
-
您的
div
没有高度/填充,这意味着它以 0px 的高度渲染。这意味着您的div
不可见,因此不会显示背景。 -
display: 100%;
无效 - 不确定这是要完成什么。 -
background
速记语法要求在大小和位置之间/
。
.front-page {
height: 300px;
width: 100%;
border: 0;
background: url("http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg") no-repeat center/cover;
}
<div class="front-page">
</div>
如果您将position
和size
放在单独的行上并放在某个高度,它可以:)(当然删除display: 100%
(
如果您更喜欢在一行上,@avril是正确的。
.front-page {
width: 300px;
height: 200px;
background: url('https://i.ytimg.com/vi/sS2JdeMNoRc/0.jpg') no-repeat;
background-position: center;
background-size: cover;
}
<body>
<div class="front-page">
</div>
</body>
CSS 语法
背景:BG-颜色 BG-图像位置/BG 大小 BG 重复 BG 原点 BG 剪辑 BG 附件 初始|继承;
cover
属性是问题所在,display: 100%;
无效。
尝试
.front-page {
...
height: 100%;
background: url(classroom.jpg) center/cover no-repeat;
...
}
或
.front-page {
...
height: 100%;
background: url("classroom.jpg") no-repeat center;
background-size: cover;
...
}