margin:auto;
在块级元素的水平居中上经常被使用的。但是你有没有想过它是如何工作的以及为什么不能使?要回答这个问题,我们首先需要看一下margin:auto;
的工作原理。
auto
会因为所在元素、元素类型和上下文的有不同不一样的表现。但是在margin
(外边距)中,auto
只有两种选择:占据可用的空间(take up the available space)或者等同于0px。这就决定了元素会有不同的布局。
auto
占据可用的空间
这是我们在使用margin:auto;
中最常见的用法。它给一个元素的左外边距和右外边距赋予同样的auto
值,那么这个元素的左、右外边距就会平分所占据的可用空间(父元素宽度的1/2),因此我们会看到在元素表现水平居中。
然而它仅仅能在水平的auto
(外边距)中起作用,在浮动元素(float)和内联元素(inline)中是不起作用的。在块级元素中,如果position
的属性设置了absolute
或者fixed
值,它也不会起到作用。
例子1:水平居中
<div class="father">
<div class="son"></div>
</div>
<style>
.father{
width: 200px;
height: 200px;
background: pink;
}
.son {
width: 100px;
height: 100px;
background: gray;
margin: auto;
}
</style>
例2:position
属性设置为absolute
<style>
.father{
width: 200px;
height: 200px;
background: pink;
}
.son {
position: absolute;
width: 100px;
height: 100px;
background: gray;
margin: auto;
}
</style>
2.使用auto
模拟float属性
因为auto
的左、右外边距平分父元素宽度,如果仅给左、右外边距其中一个赋值为auto
将会出现什么情况呢?左外边距或者右外边距将占据所有的可用空间,看起来元素好像向右或向左浮动了。
例3:模拟元素向右浮动
<style>
.father{
width: 200px;
height: 200px;
background: pink;
}
.son {
width: 100px;
height: 100px;
background: gray;
margin:0px 0px 0px auto;
}
</style>