【问题标题】:Centering a single child div horizontally and vertically on the page在页面上水平和垂直居中单个子 div
【发布时间】:2017-05-01 03:21:09
【问题描述】:

孩子水平居中,但不是垂直居中。我认为这是因为示例容器需要设置高度。如果我希望它集中在整个页面上怎么办?

请看下面的代码-sn-p

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

.example-child {
  width: 100px;
  height: 100px;
  background-color: orange;
}
<div class="example-container">
  <div class="example-child">
    <p>Sample Content...</p>
  </div>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    默认情况下,它的高度只会和孩子一样大。添加 height: 100vh 或任何适合您布局的内容。

    body { margin: 0; }
    
    .example-container {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
    }
    
    .example-child {
      width: 100px;
      height: 100px;
      background-color: orange;
    }
    <div class="example-container">
      <div class="example-child">
        <p>Sample Content...</p>
      </div>
    </div>

    【讨论】:

      【解决方案2】:

      在页面上水平和垂直居中单个子 div

      使用transform 代替flexbox 可以用更少的标记和更广泛的浏览器支持来完成

      .example-container {
        position: absolute;
        top: 50%; left: 50%;
        transform: translate(-50%,-50%);
        width: 100px;
        height: 100px;
        background-color: orange;
      }
      <div class="example-container">
          <p>Sample Content...</p>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-10
        • 2015-08-29
        • 1970-01-01
        • 2020-05-28
        • 1970-01-01
        • 1970-01-01
        • 2019-07-15
        相关资源
        最近更新 更多