Margin-top/bottom not works the to margin-left/right in a sample

人盡茶涼 提交于 2019-12-24 05:22:00

问题


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


回答1:


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 */



回答2:


I tried below

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


来源:https://stackoverflow.com/questions/28960204/margin-top-bottom-not-works-the-to-margin-left-right-in-a-sample

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!