【问题标题】:CSS - How to completely center one box in another one?CSS - 如何将一个盒子完全居中在另一个盒子中?
【发布时间】:2016-10-28 15:30:53
【问题描述】:

我作为初学者学习 css 并做一些基本测试。我的问题是:鉴于下面的 css,我如何将 box2 定位在 box1 的正中间?

.box1 {
  background: black;
  height: 400px;
  width: 400px;
  margin: auto;
}

.box2 {
  height:300px;
  width:300px;
  background: red;
  margin: auto;
}

一开始我想给 box2 一个自动边距,这样 box2 与顶部和底部的距离相等,但我得到了这个结果。

看起来它为左右设置了自动边距,但没有为顶部和底部设置边距。

所以,如果我自己给一个边距,它会像这样工作。

代码:

.box2 {
   margin: 20px auto;
}

如何使 box2 完全位于 box1 的中心?

【问题讨论】:

    标签: css margin


    【解决方案1】:

    .box1 {
    background: black;
    height: 400px;
    width: 400px;
    margin: auto;
    }
    
    .box2 {
    height:300px;
    width:300px;
    background: red;
    position:relative;
    left:12.5%;
    top:12.5%;
    }
    <div class="box1">
    <div class="box2">
    
    </div>
    </div>

    试试这个。

    【讨论】:

      【解决方案2】:

      .box1 {
      background: black;
      height: 400px;
      width: 400px;
      display:flex;
      justify-content:center;
      align-items: center;
      }
      
      .box2 {
      height:300px;
      width:300px;
      background: red;
      }
      <div class="box1">
      <div class="box2"></div>
      </div>

      【讨论】:

        【解决方案3】:

        您可以使用flexbox 来做到这一点

        .box1 {
          background: black;
          height: 400px;
          width: 400px;
          margin: auto;
          display:flex;
          align-items: center;
          justify-content: center;
        }
        
        .box2 {
          height:300px;
          width:300px;
          background: red;
          margin: auto;
        }
        <div class="box1">
          <div class="box2">
          </div>
        </div>

        【讨论】:

          【解决方案4】:
          .box1 {
            position:relative;
            background: black;
            height: 400px;
            width: 400px;
            margin: auto;
          }
          
          .box2 {
            position:absolute;
            height:300px;
            width:300px;
            background: red;
            left:50%;
            top:50%;
            transform: translate(-50%, -50%);
          }
          

          检查小提琴:https://jsfiddle.net/wh4yqk2y/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-02-26
            • 1970-01-01
            • 2021-07-24
            • 2016-05-21
            • 1970-01-01
            • 2017-02-04
            • 2020-05-31
            • 2020-10-19
            相关资源
            最近更新 更多