如何在弹性项目中精确定位div

时间:2016-10-20 16:22:00

标签: css flexbox

我正在使用flexboxes在一行中传播3个盒子。他们都是ul和li。正如所宣传的那样,我把图像放在了li中,并且它们都很好地传播。

当我在我的弹性项目中放置几个​​绝对框时,会出现问题,其中包含文本。这些绝对div从flex项中取出并定位到行的开头。

我找到的一个解决方法是使用相对div而不是绝对div,将它放在我的图像下方并使用它的top属性,将其移动到我的图像上方,但在图像下方留下一个空的白色行。

所以我想知道在flex项目中精确定位元素的“官方”方式是什么?

1 个答案:

答案 0 :(得分:1)

没有代码,甚至没有图形来说明所需的结果,这个答案在黑暗中有点像。

我要做的主要假设是你想在图像上叠加文字。如果这个假设成立,那么你使用flexbox的事实不应成为一个问题。

通常,当您想要在图像顶部叠加文本时,您可以绝对定位它,并且为了防止绝对定位在父元素之外呈现,您将父元素设置为position: relative;

备注:

  • 如果有与图像和文字相关联的其他内容,有时您可能需要为图像和文本叠加层创建一个包含元素。
  • 您可能还必须将包含图像的元素设置为内联,以便包含父元素的元素与图像的大小匹配。

这是我的建议:



ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
ul {
  display: flex;
  justify-content: space-around;
}
li {
  position: relative;
}
.overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

<ul>
  <li>
    <img src="http://placehold.it/100x100/ffcc00/?text=1">
    <div class="overlay">
      Text Overlay 1
    </div>
  </li>
  <li>
    <img src="http://placehold.it/100x100/ffcc00/?text=2">
    <div class="overlay">
      Text Overlay 2
    </div>
  </li>
  <li>
    <img src="http://placehold.it/100x100/ffcc00/?text=3">
    <div class="overlay">
      Text Overlay 3
    </div>
  </li>
</ul>
&#13;
&#13;
&#13;

如果还有与图片和文字叠加相关的其他内容,请举例说明。

&#13;
&#13;
ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
  text-align: center;
}
ul {
  display: flex;
  justify-content: space-around;
}
li .intro {
  position: relative;
}
.overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
&#13;
<ul>
  <li>
    <div class="intro">
      <img src="http://placehold.it/100x100/ffcc00/?text=1">
      <div class="overlay">
        Text Overlay 1
      </div>
    </div>
    <p>
      Some content here. Some content here. Some content here. Some content here.
    </p>
    <p>
      Some content here. Some content here. Some content here. Some content here.
    </p>
  </li>
  <li>
    <div class="intro">
      <img src="http://placehold.it/100x100/ffcc00/?text=2">
      <div class="overlay">
        Text Overlay 2
      </div>
    </div>
    <p>
      Some content here. Some content here. Some content here. Some content here.
    </p>
    <p>
      Some content here. Some content here. Some content here. Some content here.
    </p>
  </li>
  <li>
    <div class="intro">
      <img src="http://placehold.it/100x100/ffcc00/?text=3">
      <div class="overlay">
        Text Overlay 3
      </div>
    </div>
    <p>
      Some content here. Some content here. Some content here. Some content here.
    </p>
    <p>
      Some content here. Some content here. Some content here. Some content here.
    </p>
  </li>
</ul>
&#13;
&#13;
&#13;