图片作为背景在flex box中的相对位置

Relative position of picture as background in flex box

我想在不继承子框的容器中制作一个不透明的图像作为背景。

我的代码:

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 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 不适用于绝对定位的元素,因为这些元素会创建新的块格式上下文:BFC link

我通过将 position: absolute; 放入容器并在图像上将 position: relative; 更改为 position: absolute; 并将框上的 position: absolute; 更改为 position: relative; 来修复我的代码。

嗯,看来我对position 属性的理解还不够。所以我很感激,如果有人能回答,为什么它以前不起作用。