【问题标题】:Margin-top/bottom not works the to margin-left/right in a sample上边距/下边距不适用于样本中的边距左/右
【发布时间】:2015-05-11 16:24:08
【问题描述】:

我是 HTML 和 CSS 的新手。 我试过下面的代码

<!DOCTYPE html>

<html>
<head>
<title>Center</title>
</head>

<body>
    <div id="div1" style="width:300;background-color:olive">
        <div id="div2" style="width:100px; margin-left:auto; margin-right:auto; background-color:gray"></div>
    </div>  
</body>

</html>

“div2”水平居中。

然后我将宽度更改为高度并将边距左/右更改为边距顶部/底部。 (下面的代码)

<!DOCTYPE html>

<html>
<head>
<title>Center</title>
</head>

<body>
    <div id="div1" style="height:100px;background-color:olive">
        <div id="div2" style="height:20px; margin-top:auto; margin-bottom:auto; background-color:gray"></div>
    </div>  
</body>

</html>

它没有像我预期的那样垂直居中。

任何人都可以帮我解释一下,为什么他们没有相同的行为? 谢谢, 黄

【问题讨论】:

  • 垂直居中不像水平那么容易。 automargin-top/bottom 什么都不做。
  • 你知道为什么它的行为与逻辑不同吗?
  • 我不是 CSS 规范的作者,但作为一名开发人员,我从来不需要通过这种方式垂直居中

标签: html css margin


【解决方案1】:

margin-auto 仅适用于水平边距。即margin-left and right

您无法将垂直边距设置为自动。相反,您可以将其设为内联块并将其垂直居中设置。阅读this answer

MDN says:

margin: auto;  /* box is horizontally centered, 0 margin on top and bottom */

【讨论】:

    【解决方案2】:

    我在下面尝试过

    <!DOCTYPE html>
    
    <html style="height:100%">
    <head>
    <title>Center</title>
    </head>
    
    <body style="height:100%; width:100%">
        <div style="display:table; width:100%; height:100%">
            <div id="div1" style="display:table-cell;vertical-align:middle">
                <div id="div2" style="display:table-cell;vertical-align:middle;height:20px; margin:0 auto; background-color:gray">Text is vertical alignment</div>
            </div>
        </div>  
    </body>
    
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2014-02-27
      • 2017-11-21
      • 2013-09-02
      • 1970-01-01
      • 2022-01-26
      • 2016-09-29
      相关资源
      最近更新 更多