Div margin:auto vs align:center

时间:2016-07-12 20:05:25

标签: html5 twitter-bootstrap css3

我彼此之间有两个div。我希望他们两个都水平居中。问题是,我必须align: center使用#wrapper而另一个使用margin: auto。否则只有其中一个居中。如果我同时使用align-center,那么只有#wrapper居中,如果我同时使用margin: auto,则只有第二个居中。

为什么我必须使用2个不同的属性将它们对齐在中心?:

HTML:

<div class="col-sm-5 col-sm-offset-3" id="wrapper">
    <div class="row">
       <div class="col-sm-1 col-sm-offset-2" id="col1"> col1 </div>
       <div class="col-sm-1 col-sm-offset-2 " id="col2"> col2 </div>
       <div class="col-sm-1 col-sm-offset-2" id="col3"> col3 </div>
   </div>
</div>

<div id="below">
Centered div below the #wrapper div
</div>

CSS:

html, body{
    height:100%;
}
#col1{
    background-color: lime;
    border: solid 1px;
    text-align: center;
}
#col2{ 
    background-color:  aqua;
    border: solid 1px;
    text-align: center;
}
#col3{
    background-color:  lightpink;
    border: solid 1px;
    text-align: center;
}
#wrapper{
    border: solid 1px;
    height: 10%;
    width: 50%;
    align: center;
}

#below{
    border: solid 2px;
    text-align: center;
    min-height: 100%;
    width: 80%;   
    clear: both;  
    margin: auto;
}

2 个答案:

答案 0 :(得分:3)

align不是有效的CSS属性 - 它是<table>元素上可用的属性,但不鼓励使用该属性:https://developer.mozilla.org/en/docs/Web/HTML/Element/table#Attributes

在CSS中使用align应该没有效果。

margin: 0 auto;直接影响容器,当容器是块级别(display: block)时。

text-align: center会影响容器的text,inline和inline-block level children - 而不是容器本身。

区分两者非常重要:

以块级元素为中心:使用margin: 0 auto;

将文本,内嵌或内联块级别的子项居中:使用text-align: center;

鉴于此,请检查#wrapper是否为块级,即display: block。如果它不是,或者它的父母会抑制它的宽度,那么它不会以保证金为中心,除非你进入display: flex世界,你不应该真正探索直到你掌握了块和内联块级元素的基础知识。

我写过一篇文章,解释如何利用基本的显示属性,并辅以交互式Codepen演示:http://fixate.it/blog/css-display-properties/

答案 1 :(得分:1)

Div margin:auto vs align:center

margin: 0 auto什么时候可以使用它?
您何时需要设置中心对齐任何div或任何阻止,例如主要父container,在这种情况下,您必须margin: 0 auto使用display: table它将设置您的部门中心父母部分。


text-align: center什么时候可以使用它?
在这种情况下,您何时需要设置中心对齐Text ParagraphImage,您必须使用text-align: center它将设置文本段落或图像中心