一、一行文本水平和垂直居中
- 水平居中:
text-align:center
- 垂直居中:
line-height:父元素的高
二、行内元素水平和垂直居中
- 水平居中:
- 给父元素添加
text-align:center
- 行内元素没有脱离文档流(absolute,fixed,float)
- 给父元素添加
- 垂直居中
- 法一:给父元素添加
padding-top:((父height - 子height) / 2)px
- 法二:给子元素添加
position:absolute;top:50%;margin-top:-(子height/2)px;
- 法一:给父元素添加
- 水平垂直居中
- 给父元素添加
text-align:center
,padding-top:((父height - 子height) / 2)px
- 如果需要保持原有的容器高度,则父元素的高度需要减去padding-top
- 给父元素添加
三、块元素的水平和垂直居中
-
子元素或父元素加定位或者浮动或者父元素设置边框;子元素添加
margin:((父height - 子height) / 2)px auto
-
父相对子绝对
- 法一:position + 负margin
/*子元素添加*/ position:absolute; top:50%; margin-top:-((子height) / 2)px; left:50%; margin-left:-((子width) / 2)px;
- 法二:position + margin
/*子元素添加*/ position:absolute; margin:auto; left:0; top:0; right:0; bottom:0;
-
position + calc()
#box{width: 300px;height: 300px;background: pink;position: relative;} #box1 {width: 100px;height: 100px;position: absolute;background-color: yellow;top: calc(50% - (子height/2)px);left:calc(50% - (子width/2)px);} <div id="box"> <div id="box1"></div> </div>
-
position + transform
#box{width: 300px;height: 300px;background: pink;position: relative;} #box1 {width: 100px;height: 50px;background:green;position: absolute;top: 50%;left:50%;transform: translate(-50% , -50%);} <div id="box"> <div id="box1"></div> </div>
-
弹性盒
#box{width: 300px;height: 300px;background: pink;display: flex;justify-content: center;align-items: center;} #box1 {width: 100px;height: 50px;background:green;} <div id="box"> <div id="box1"></div> </div>
-
父:table-cell 子:inline-block
#box {width: 300px;height: 300px;background: yellow;display: table-cell;vertical-align: middle;text-align: center;}
#box1 {width: 100px;height: 50px;background: green;display: inline-block;}
<div id="box">
<div id="box1"></div>
</div>
四、表格的水平垂直居中
text-align: center;vertical-align: middle;
五、图片的水平垂直居中
- 基本布局:div>img+span
- css样式:
- 父元素添加:text-align:center;
- img添加:vertical-align:middle;
- span作为参考物添加:
- display: inline-block;
- height: 100%;
- vertical-align: middle;
#box{width: 300px;height: 300px;background: pink;text-align: center;}
#box img{vertical-align: middle;width: 200px;height: 200px;}
#box span{display: inline-block;height: 100%;vertical-align: middle;}
六、图片下方间隙解决办法
- 法一:
img{vertical:top / middle / bottom}
- 法二:
img{display:block}
- 法三:
img{float:left / right}
- 法四:
父元素{font-size:0}