我希望div类item2漂浮在背景图片上,
但是失败了。我该如何解决?
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;
}

下面是我想要的
css - CSS Div float 在Flex背景图片上-LMLPHP

最佳答案

这是我添加的新代码:

/* 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;
}


基本上,我给图像一个相对的位置,两个重叠的divs都给一个绝对位置,然后正确定位它们。我还给了他们0.7的不透明度,以便您可以看到它们在图像上方:



.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>

07-24 09:31