我想在div
中展示background-image
。我尝试使用img
以相同的方式执行此操作,但它不起作用:
在IMG内
HTML
<img class="scale" src="../../../assets/images/van-landing-2.JPG">
CSS
.scale {
max-width: 100%;
height: auto;
width: auto\9;
/* ie8 */
}
这非常有效。它显示的图像占据了我的屏幕的100%,高度应该是成比例的。
照片
然而,当我尝试使用div时,它不起作用。它没有显示任何导致它没有设置特定高度,因此它什么也没显示。
在DIV之内
HTML
<div class="i-van"></div>
CSS
.i-van {
background-image: url("../../../assets/images/van-landing.JPG");
max-width: 100%;
height: auto;
width: auto\9;
/* ie8 */
}
照片
我怎么能这样做?我尝试过使用min-height
并显示它但只是最小高度。我想展示一切。
您必须声明背景div的有效高度。正如Maneesh所说,height:auto
取得了元素含量的高度。
检查片段! :)
使用FLEXBOX的代码
body {
margin: 0;
}
.i-van {
display: flex;
align-items: center;
justify-content: center;
background-image: url(https://www.planwallpaper.com/static/images/3865967-wallpaper-full-hd_XNgM7er.jpg);
background-size: cover;
background-position: center;
max-width: 100%;
height: 100vh;
}
#div-inside {
font-size: 100px;
color: white;
}
<div class="i-van">
<div id="div-inside">
HELLO
</div>
</div>
具有位置绝对的代码
body {
margin: 0;
}
.i-van {
position: relative;
background-image: url(https://www.planwallpaper.com/static/images/3865967-wallpaper-full-hd_XNgM7er.jpg);
background-size: cover;
background-position: center;
max-width: 100%;
height: 100vh;
}
#div-inside {
position: absolute;
top: 50%;
/* position the top edge of the element at the middle of the parent */
left: 50%;
/* position the left edge of the element at the middle of the parent */
transform: translate(-50%, -50%);
/* This is a shorthand of translateX(-50%) and translateY(-50%) */
font-size: 100px;
color: white;
}
<div class="i-van">
<div id="div-inside">
HELLO
</div>
</div>
background-image
属性用于向元素添加背景。这意味着该元素中的内容决定了它的大小。此外,height:auto
由元素内容解释。
你可以尝试使用height:100%
,前提是父元素也有定义的高度值。这会将元素拉伸到最高的高度并相应地缩放背景图像。
如果您希望以图像本身的精确尺寸或纵横比显示图像,则需要使用图像的精确width
和height
定义该元素。
但是,从语义角度来看,您应该确定您显示的图像是页面内容的一部分还是设计的装饰部分。一般来说,你应该使用<img />
标签作为内容的图像,background-image
作为非图像的图像。
您可以了解更多有关background-image here的信息