【问题标题】:Why margin auto is not able to center item vertically? [duplicate]为什么margin auto不能垂直居中? [复制]
【发布时间】:2022-01-14 16:16:40
【问题描述】:

我想我对自动边距的工作方式有些困惑。在这种情况下,我在其中创建了一个父 div 和一个子 div,并且两个 div 框都指定了宽度和高度。然后,我尝试使用自动边距使内部 div 水平和垂直对齐。

<div id="parent">
    <div id="child"></div>
</div>
#parent {
  width: 200px;
  height: 200px;
  background: red;
}

#child {
  width: 50%;
  height: 50%;
  background: blue;
  margin: auto;
}

结果:

不知何故,结果出乎我的意料。有谁知道为什么?

【问题讨论】:

    标签: html css margin


    【解决方案1】:

    只需使用display: flex

    #parent {
      width: 200px;
      height: 200px;
      background: red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    #child {
      width: 50%;
      height: 50%;
      background: blue;
    }
    <div id="parent">
        <div id="child"></div>
    </div>

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 2010-11-01
      • 2012-01-27
      • 2021-06-26
      • 2017-11-29
      • 2018-09-04
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多