居中总结

2020-04-26 09:50发布

居中:盒子在其包含块中居中

1.行盒(行块盒)水平居中:

直接设置行盒(行块盒)父元素的text-align属性:center

 

2.常规流块盒水平居中:

定宽,设置左右margin为auto;

div{

  width:100px;

  margin:0 auto;

}

 

3.绝对定位的水平居中:

定宽,设置左右的坐标为0(left:0, right:0),将左右的margin设置为auto

div{

  width:100px;

  left:0;

  right:0;

  margin:0 auto;

}

 

3.单行文本垂直居中

设置文本所在的元素的行高,为整个区域的高度:line-height:100px;

 

4.行块盒或块盒内多行文本的垂直居中

没有完美解决方案

设置盒子上下内边距(padding)相同,来达到类似的效果

也可以使用下面5所介绍的垂直居中方案。

 

5.绝对定位的垂直居中

定高,设置上下的坐标为0(top:0, bottom:0),将上下margin设置为auto