Search code examples
cssflexboxbackground-image

Css div float on the flex backgroud image


I want the div class item2 float on the backgroud image, but it fails. How can I solve this?

https://codepen.io/robinnpca/pen/QXKrON

html

<div class="flex_img" >
      <div class="item2 ">
        <div >up1</div>
        <div >up2</div>
      </div>
      <div class="item2 ">
        <div >down1</div>
        <div >down2</div>
      </div>
    </div>

css

.item2{
  flex: 1 1 100%;
  background-color: #f08bc3;
   display: flex;
  justify-content: space-between;
}

.flex_img {
  flex: 0 0 100%;
  background-color: #f08bc3;
  width:100%;
  height:175px;
  display: flex;
  flex-direction: row;
  flex-wrap:wrap;
  align-content:space-between;
  background-image:  url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
                  url("https://mdn.mozillademos.org/files/7693/catfront.png");
  background-color: transparent;
  background-position: center;
  background-position:left; 
}

below is I want enter image description here


Solution

  • This is the new code I added:

    /* New Code */
    
    .flex_img {
      position: relative;
    }
    
    .item2{
      position: absolute;
      width: 100%;
      opacity: 0.7;
    }
    
    .item2:nth-of-type(1){
      top: 0;
    }
    
    .item2:nth-of-type(2){
      bottom: 0;
    }
    

    Basically, I gave the image a position of relative and the two overlaid divs a position of absolute, then positioned them correctly. I also gave them a .7 opacity so you can see that they're over the image:

    .item2{
      flex: 1 1 100%;
      background-color: #f08bc3;
       display: flex;
      justify-content: space-between;
    }
    
    .flex_img {
      flex: 0 0 100%;
      background-color: #f08bc3;
      width:100%;
      height:175px;
      display: flex;
      flex-direction: row;
      flex-wrap:wrap;
      align-content:space-between;
      background-image:  url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
                      url("https://mdn.mozillademos.org/files/7693/catfront.png");
      background-color: transparent;
      background-position: center; 
      background-position:left; 
    }
    
    /* New Code */
    
    .flex_img {
      position: relative;
    }
    
    .item2{
      position: absolute;
      width: 100%;
      opacity: 0.7;
    }
    
    .item2:nth-of-type(1){
      top: 0;
    }
    
    .item2:nth-of-type(2){
      bottom: 0;
    }
       <div class="flex_img" >
          <div class="item2 ">
            <div >up1</div>
            <div >up2</div>
          </div>
          <div class="item2 ">
            <div >down1</div>
            <div >down2</div>
          </div>
        </div>