使用flexbox将绝对定位的div置于另一个div中心

5

使用css进行居中处理时,我希望将一个div绝对定位在另一个div内居中,实现的效果如下图所示:

expected

最好使用flexbox,以下是示例代码:

.abs_1 {
  position: absolute;
  background: red;
  height: 200px;
  width: 200px;
  top: 40px;
  left: 40px;
}

.abs_2 {
  position: absolute;
  background: blue;
  height: 200px;
  width: 200px;
  top: 60px;
  left: 250px;
}

.center{
    display: flex;
    justify-content: center;
    align-items: center;
}

.center div {
  background: black;
  color: white;
}
<div class="abs_1">
  <div class="center">
      <div>Hello.</div>
  </div>
</div>

<div class="abs_2">
  <div class="center">
      <div>World</div>
  </div>
</div>

我得到了以下内容:

我得到了以下内容:

wrong

您能使用flex css来完成这个吗?

1个回答

6

这里是使用CSS Flexbox的解决方案。

CSS

#container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.abs_1 {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px;
    background: red;
    height: 200px;
    width: 200px;
}

.abs_2 {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px;
    background: blue;
    height: 200px;
    width: 200px;
}

.center > div {
    background: black;
    color: white;
}

HTML

<div id="container">

    <div class="abs_1">
        <div class="center">
            <div>Hello.</div>
        </div>
    </div>

    <div class="abs_2">
        <div class="center">
            <div>World</div>
        </div>
    </div>

</div><!-- end #container -->

演示:http://jsfiddle.net/3ekyetc0/


1
虽然问题是关于将具有 position: absolutediv 居中在其他 div 容器内,而不是让其消失。 - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接