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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:27:21  来源:igfitidea点击:

css center div inside container?

htmlclasscenter

提问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-alignnot alignlike 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.

如果您想让块元素(如divpul等...)居中,您需要设置其宽度并将水平边距设置为auto

For example, the following code will make every div inside an element with the MyContainerclass 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%;
}

jsFiddle Demo

jsFiddle 演示