Fork me on GitHub

css3

css中各种居中方法总结

水平居中=>行内元素、块状元素
块状元素=>定宽、不定宽

水平居中

行内元素
text-align:center;=>
设置文本居中的方式。用于行内元素水平居中;
但是也可以用来使块级元素中的文本水平居中;
块状元素居中
margin
margin:0 auto;=>width为固定值时可用;
position
设置子元素position为absolute,left:50%;
1.(定宽高)=>margin-left:-50%;(后面的-50%是相对子元素的具体数值);
2.(定宽高)=>left=right;top=bottom;
3.(不定宽高)=>transform:translateX(-50%);
4.(不定宽高)=>left:0;right:0;top:0;bottom:0;margin:auto;
flex
justify-content: center;(不定宽高)
table
margin:0 auto;=>可以使子元素宽度不固定时使用,原理应该就是table\table-cell元素具有包裹性(个人观点)

垂直居中

line-height
height=line-height;
只适用于单行文本
vertical-align
要设置父元素为display:table\table-cell;才可以使用vertical-align
button标签
button标签中的块级元素默认是垂直居中的
flex
align-tiems:center;
pisition方法同水平居中

####水平垂直居中

text-align+line-height;
button居中;
table-cell居中;
margin固定宽高居中;
负margin居中;
transform居中;
绝对定位居中;
flex居中;  
不确定宽高居中(绝对定位百分数);
-------------本文结束感谢您的阅读-------------