【问题标题】:center div inside div with absolute position using flexbox使用 flexbox 在 div 中以绝对位置居中 div
【发布时间】:2015-06-14 09:18:22
【问题描述】:

使用 css 的其他问题中心,我希望在其他 div 中以绝对位置居中,我希望得到与此图像类似的结果:

最好使用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>

我得到以下信息:

你能用 flex css 做到这一点吗?

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    这是一个使用 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/

    【讨论】:

    • 以为问题是关于将 div 居中在其他 div 容器中,而 position: absolute 不可可移动
    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    相关资源
    最近更新 更多