保证金顶部/底部不适用于样本中的保证金左/右 [英] Margin-top/bottom not works the to margin-left/right in a sample

查看:109
本文介绍了保证金顶部/底部不适用于样本中的保证金左/右的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是HTML新手, CSS。
我试过了下面的代码:

 <!DOCTYPE html> 

< html>
< head>
< title>中心< /标题>
< / head>

< body>
< div id =div1style =width:300; background-color:olive>
< div id =div2style =width:100px; margin-left:auto; margin-right:auto; background-color:gray>< / div>
< / div>
< / body>

< / html>

div2横向居中。

然后,我将宽度更改为高度&空白左/右至页边/底部。 (下面的代码)

 <!DOCTYPE html> 

< html>
< head>
< title>中心< /标题>
< / head>

< body>
< div id =div1style =height:100px; background-color:olive>
< div id =div2style =height:20px; margin-top:auto; margin-bottom:auto; background-color:gray>< / div>
< / div>
< / body>

< / html>

它并不像我预期的那样垂直居中。

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

解决方案

margin-auto 仅适用于水平边距。即左右保证金



您无法将垂直边距设置为自动。相反,您可以将其设置为内嵌块并将其垂直设置为中间。阅读这个答案



MDN says

  margin:auto; / *框为水平居中,顶部和底部为0空白* / 


I am new to HTML & CSS. I have tried the code below

<!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>

The "div2" is in centered horizontally.

Then I change the width to height & margin-left/right to margin-top/bottom. (the code below)

<!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>

It is not centered vertically as I expected.

Any can help me to explain this, why they don't have the same behaviors? Thanks, Hoang

解决方案

margin-auto only works on horizontal margin. i.e margin-left and right.

There is no way you can set vertical margin to auto. instead you can make it an inline block and set it vertically middle. read this answer

MDN says:

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

这篇关于保证金顶部/底部不适用于样本中的保证金左/右的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆