我想制作一个不透明的图像作为容器中的背景,而不继承给子框。
我的代码:
body{
background-color: black;
color: white;
font-size: 30px;
text-align: center;
justify-content: center;
}
.container{
border-color: white;
border-style: solid;
border-width: 2px;
display: flex;
width: 300px;
min-height: 300px;
justify-content: center;
flex-direction: column;
}
.box{
opacity: 0.2;
border-color: white;
border-style: solid;
border-width: 2px;
flex: 1;
}
.box1{background-color: yellow;}
.box2{background-color: green;}
.box3{background-color: blue;}
.box4{background-color: red;}
.box5{background-color: orange;}
.container img{
width: 100%;
opacity: 0.3;
}
<body>
<div class="container">
<img src="http://www.tapeciarnia.pl/tapety/normalne/191848_swiecace_kule_grafika_3d.jpg" alt="">
<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
<div class="box box3">Box 3</div>
<div class="box box4">Box 4</div>
<div class="box box5">Box 5</div>
</div>
</body>
我想将这些彩色框放在该图像上,但是当我尝试将 position: relative;
与 z-index: -1;
一起使用时到图像和 position: absolute;
到盒子然后 flex 定位不起作用。
您能解释一下为什么 flex box 不能使用绝对定位并给出该问题的解决方案吗?
最佳答案
当您将 position: relative
设置为 .container
并将 position: absolute
设置为 .container img< 时,它似乎工作正常
。
body{
background-color: black;
color: white;
font-size: 30px;
text-align: center;
justify-content: center;
}
.container{
border-color: white;
border-style: solid;
border-width: 2px;
display: flex;
width: 300px;
min-height: 300px;
justify-content: center;
flex-direction: column;
position: relative;
}
.box{
opacity: 0.2;
border-color: white;
border-style: solid;
border-width: 2px;
flex: 1;
}
.box1{background-color: yellow;}
.box2{background-color: green;}
.box3{background-color: blue;}
.box4{background-color: red;}
.box5{background-color: orange;}
.container img{
position: absolute;
width: 100%;
opacity: 0.3;
}
<body>
<div class="container">
<img src="http://www.tapeciarnia.pl/tapety/normalne/191848_swiecace_kule_grafika_3d.jpg" alt="">
<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
<div class="box box3">Box 3</div>
<div class="box box4">Box 4</div>
<div class="box box5">Box 5</div>
</div>
</body>
我认为 flexbox 不适用于绝对定位的元素,因为这些元素会创建新的 block 格式上下文:BFC link
关于css - 图片作为背景在flex box中的相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41915601/