Html 容器内的css中心div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18814940/
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
css center div inside container?
提问by Marco Tck
This HTML code works:
此 HTML 代码有效:
<div class="MyContainer" align="center">
<div>THIS DIV IS CENTERED</div>
</div>
But I would like to do it at the css of the container, something like:
但我想在容器的 css 中执行此操作,例如:
.MyContainer{
align: center;
}
So all my containers will center the divs inside.
所以我所有的容器都将里面的 div 居中。
回答by Itay
The CSS property for the text alignis called text-align
not align
like in the inline DOM attribute.
对CSS属性的文本对齐被称为text-align
没有align
像内联DOM属性。
If you want to center a block element(like div
, p
, ul
, etc...) itself you need to set its width and set the horizontal margins to auto
.
如果您想让块元素(如div
、p
、ul
等...)居中,您需要设置其宽度并将水平边距设置为auto
。
For example, the following code will make every div inside an element with the MyContainer
class 80% the size of its parent and center it in the middle of its container.
例如,以下代码将使MyContainer
类元素中的每个 div为其父元素的80% 大小,并将其居中放置在其容器的中间。
.MyContainer div {
margin: 0 auto;
width: 80%;
}