一、文本居中
左右居中:
text-align:center;
上下居中:
line-height:(height数值);
二、块元素居中
方法一:
margin:auto;
让盒子左右居中。
方法二:
position:absolute;
left:50%;
margin-left:-(宽的一半);
top:50%;
margin-top:-(高的一半);
让盒子上下左右居中。
缺点:不够智能,若盒子的宽高改变,则需要改变相应的margin值。
方法三:
position;absolute;
left:50%;
tranform:translateX(-50%);
top:50%;
tranform:translateY(-50%);
利用位移让盒子居中,位移50%是基于盒子自身的宽高。
跟方法二相比,这种方法更为智能。
方法四:
父元素{
display:flex;}
子元素{
margin:auto;}
在flex布局中,margin:auto;会让元素的上下左右都生效。
注意:应用flex布局,会影响到父元素内部所有子元素的布局。
方法五:
margin:auto;
position:absolute:
left:0;
right:0;
top:0;
bottom:0;