一.水平居中元素
1.通用方法,元素的宽度高度未知
方法1:css3 transform
.parent { position: relative; } .child { position: absolute; /*子元素绝对定位*/ left: 50%: /*距左边50%*/ transform: translateX(-50%); /*左偏移-50%*/ }
方法2:flex布局
.parent { display: flex; /*flex布局*/ justify-content: center; /*子元素居中*/ }
适用于子元素浮动,绝对定位,内联元素。
2.居中元素为内联元素(display:inline)
常见的内联元素有:span,a,img,input,label等
.parent { text-align: center; /*内联子元素直接居中*/ }
3.居中元素为块级元素(display:block)
常见的块元素:div,h1~h6,p,ul,li等
方法1:设置margin
.parent { width: 100%; } .child { width: 600px; height: 50px; margin: 0 auto; /*块元素margin居中方法*/ background: #999; }
方法2:修改为inline-block属性
.parent { text-align: center; /*内联子元素居中*/ } .child { display: inline-block; /*子元素转换内联属性*/ }
4.居中元素为浮动元素
.child { width: 100px; float: left; /*子元素浮动*/ position: relative; /*子元素相对定位*/ left: 50%; /*距左边50%*/ margin-left: -50px; /*宽度值一半的负值*/ }
5.居中元素为绝对定位的元素
方法1:
.parent { position: relative; } .child { position: absolute; /*子元素绝对定位*/ width: 100px; left: 50%; /*距左边50%*/ margin-left: -50px; /*宽度值一半的负值*/ }
方法2:
.parent { position: relative; } .child { position: absolute; /*子元素绝对居中*/ width: 100px; left: 0; /*左置0*/ right: 0; /*右置0*/ margin: 0 auto; /*置中*/ }
二.垂直居中元素
1.通用方法,元素宽度高度未知
方法1:css3 transform
.parent { position: relative; } .child { position: absolute; /*子元素绝对定位*/ top: 50%; /*距顶部50%*/ transform: translateY(-50%); /*上偏移-50%*/ }
方法2:flex布局
.parent { display: flex; /*flex布局*/ align-items: center; /*子元素竖直方向居中*/ }
适用于子元素浮动,绝对定位,内联
2.居中元素为单行文本
.text { line-height: 200px; /*单行文本行高=高,垂直居中了*/ height: 200px; }
3.已经知道元素宽度高度
方法1:
.parent { position: relative; } .child{ position: absolute; /*子元素绝对定位*/ top: 50%; /*距顶部50%*/ height: 100px; /*高度已知*/ margin-top: -50px; /*顶边距:高度一半的负值*/ }
方法2:
.parent { position: relative; } .child{ position: absolute; /*子元素绝对定位*/ top: 0; /*距顶部0*/ bottom: 0; /*距底部0*/ height: 100px; /*高度已知*/ margin: auto 0; /*上下边距自动相等,垂直居中了*/ }