我在CSS中有一个div结构,看起来像这样。
<div style="background-image: url(my_url.ext)>
<div>
My content 1.
<div>
<div>
My content 2.
<div>
</div>
当网站显示在移动设备上时,我希望background-image属性显示在内容div下方。我尝试使用background-position属性,但它没有扩展父div的长度,实际上隐藏了图像。有没有办法在父<img>
内没有设置单独的<div>
标记的情况下执行此操作?我的CSS类目前看起来像这样:
.myClass/root {
background-repeat: no-repeat;
height: 100%;
position: relative;
}
@media (desktop-breakpoint) {
.myClass/root {
position: relative;
}
.myClass/root .myClass/background {
background-size: cover;
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
z-index: -1;
}
}
@media (mobile-breakpoint) {
.myClass/root {
display: flex;
flex-direction: column;
min-height: 100%;
}
.myClass/root .myClass/background {
background-size: cover;
flex-grow: 1;
}
}
答案 0 :(得分:0)
这是有效的
#parent{
height:auto;
width: auto;
color:#fff;
position:relative;
}
#parent:after{
content: "";
height:100%;
width: 100%;
position: absolute;
left:0;
top:0;
background-position:center center;
background-size: cover;
background-clip: content-box;
background-image: url(https://images.pexels.com/photos/110147/pexels-photo-110147.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);
z-index:-1;
}
@media(max-width: 767px){
#parent div{
background: #000;
}
#parent:after{
content: "";
height:50px;
width: 100%;
position: relative;
display:block;
background-position:center center;
background-size: cover;
background-clip: content-box;
background-image: url(https://images.pexels.com/photos/110147/pexels-photo-110147.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);
z-index: 50;
}
}
而你的html如下
<div id="parent">
<div>
My content 1.
</div>
<div>
My content 2.
</div>
</div>