Html 如何在父div内水平居中div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1952256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center horizontally div inside parent div
提问by Eagle
How do I center a div
horizontally inside its parent div
with CSS
?
如何居中div
水平其父里面div
用CSS
?
<div id='parent' style='width: 100%;'>
<div id='child' style='width: 50px; height: 100px;'>Text</div>
</div>
回答by Mark Embling
I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.
我假设父 div 没有宽度或宽度较宽,而子 div 的宽度较小。下面将设置顶部和底部的边距为零,边距自动适应。这使 div 居中。
div#child {
margin: 0 auto;
}
回答by James Goodwin
<div id='parent' style='width: 100%;text-align:center;'>
<div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>
回答by Paul Chris Jones
Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:
只是出于兴趣,如果您想将两个或更多 div 居中(因此它们并排在中心),那么这里是如何做到的:
<div style="text-align:center;">
<div style="border:1px solid #000; display:inline-block;">Div 1</div>
<div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>
回答by x4u
You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:
您可以为左右边距使用“auto”值,让浏览器在内部 div 的两侧平均分配可用空间:
<div id='parent' style='width: 100%;'>
<div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>
回答by Soufiane Hassou
<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>