【问题标题】:Centering div that can be bigger than body可以比 body 大的居中 div
【发布时间】:2018-08-21 05:21:24
【问题描述】:

我正在开发一个包含登录/注册页面的项目。它基本上是body中的一个白色div,应该垂直和水平居中,但有时可以比body大。

当 div 很小时,一切都很好,但是当它大于 body 时,我只希望它在顶部和底部有小填充。

我怎样才能做到这一点?我整天都在寻找答案,最后我在这里。帮助我的人:C

 #wrap {
  height: 300px;
  width: 150px;

  display: flex;
  justify-content: center;
  align-items: center;

  background: #DDD;
}

#content {
  background: #000;
  width: 100px;
  height: 400px;
}
<div id="wrap">
  <div id="content"> 
  </div>
</div>

   

【问题讨论】:

  • 使用id 而不是class 进行样式设置是不好的做法

标签: html css flexbox centering


【解决方案1】:

您可以使用min-height 代替height,并在包装​​器上使用小的顶部和底部填充,如下所示。当内部元素高于 wrapper 时,它会扩展 wrapper 并额外保留 padding。

 #wrap {
  min-height: 300px;
  padding: 10px 0;
  width: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #DDD;
}
#content {
  background: #000;
  width: 100px;
  height: 400px;
}
<div id="wrap">
  <div id="content"> 
  </div>
</div>

   

【讨论】:

    【解决方案2】:

    使用min-height 代替height,并在顶部和底部添加padding。使用box-sizing: border-box防止padding改变高度:

    .wrap {
      box-sizing: border-box;
      min-height: 300px;
      width: 150px;
      padding: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    
      background: #DDD;
    }
    
    .content {
      background: #000;
      width: 100px;
      height: 400px;
    }
    
    /** for the demo **/
    .content--small {
      height: 100px;
    }
    
    body {
      display: flex;
      justify-content: space-around;
      align-items: flex-start;
    }
    <div class="wrap">
      <div class="content"> 
      </div>
    </div>
    
    <!-- for the demo -->
    <div class="wrap">
      <div class="content content--small"> 
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2012-11-19
      • 2016-03-06
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多