Search code examples
cssbackgroundpositionflexboxabsolute

Relative position of picture as background in flex box


I'd like to make an image with opacity as a background in a container without inheritance to the children boxes.

My code:

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>

I'd like to put these colorful boxes on that image, but when i'm trying to use position: relative; with z-index: -1; to image and position: absolute; to boxes then flex positioning doesn't work.

Could you explain why flex box don't work with absolutely positioning and give the solution of that problem?


Solution

  • It seems to work fine when you set position: relative to .container and position: absolute to .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>

    I think flexbox doesn't work right with absolutely positioned elements because those elements create new block formatting context: BFC link