实现水平垂直居中的方法
文本(文字)内容属于行内元素
行内元素水平垂直居中方法
方式一:
设置文字外层的盒子
text-align:center /*水平居中*/ height = 100px; /*垂直居中 */line-height = 100px;
垂直居中只要保证行高和盒子高度一致即可
代码如下:
<!DOCTYPE html><html><head><title>行高居中</title><style type="text/css">.box{width: 200px;height: 200px;text-align:center;background-color: red;line-height: 200px;}</style></head><body><div class="box">hello</div></body></html>
方式二:转换成单元格
将文字所在的盒子display
设置成table-cell
text-align:center 水平居中 display:table-cell; 垂直居中 vertical-align:middle;
注意:只有单元格元素才拥有vertical-align
属性
代码如下:
<!DOCTYPE html><html><head><title>垂直居中</title><style type="text/css">.box{width: 200px;height: 200px;text-align:center;background-color: red;display: table-cell;vertical-align: middle;}/*附:单元格居中方法*/td{width: 200px;height: 200px;background-color: green;text-align: center;}</style></head><body><div class="box">hello</div><table><tr><td>123</td></tr></table></body></html>
块级元素水平居中方法
margin:0 auto;
只能设置水平居中,而margin:auto 0
不能设置垂直居中,因为margin
垂直塌陷问题
方法一:定位+margin
父级元素设置position:relative;
儿子元素设置
width: 100px; height: 100px; position:absolute; top:50%; left:50%; margin-top:-50px; margin-right:-50px;
只要margin-left
为高度的一半,margin-right
为宽度的一半即可
代码如下:
<!DOCTYPE html><html><head><title>定位和margin法盒子居中</title><style type="text/css">.one{width: 200px;height: 200px;background-color: red;position: relative;}.two{width: 100px;height: 100px;background-color: green;/*给这个盒子定位水平垂直居中*/position: absolute;top: 50%;left: 50%;margin-top: -50px;margin-left: -50px;/*设置盒子内文字水平,垂直居中*/text-align:center;line-height: 100px;}</style></head><body><div class="one"><div class="two"><span>你好</span></div></div></body></html>
方式二:定位方法
父级元素设置position:relative;
儿子元素设置
position:absolute; top:0; bottom:0; left:0; right:0; margin:auto;
这样设置以后,浏览器将自动将上下外边距相同,左右外边距相同,达到垂直居中的效果
代码如下:
<!DOCTYPE html><html><head><title>纯定位法盒子居中</title><style type="text/css">.big{width: 200px;height: 200px;background-color: red;position: relative;}.small{width: 50px;height: 50px;background-color: green;position: absolute;margin:auto; top: 0;bottom: 0;left: 0;right: 0;}</style></head><body><div class="big"><div class="small"></div></div></body></html>
方式三:单元格方法
利用单元格法
父级元素
display:table-cell; text-align:center; vertical-align:middle;
子元素
display:inline-table
因为text-align
只对行内元素和行内块生效
代码如下:
<!DOCTYPE html><html><head><title>单元格法盒子居中</title><style type="text/css">td{width: 200px;height: 200px;background-color: red;text-align: center;vertical-align: middle;}span{display: inline-block;width: 50px;height: 50px;line-height: 50px;background-color: yellow;}div.big{width: 200px;height: 200px;background-color:purple;display: table-cell;vertical-align: middle;text-align: center;}div.small{width: 50px;height: 50px;line-height: 50px;display: inline-block;background-color: yellow;}</style></head><body><table><div class="big"><div class="small">小盒子</div></div><tr><td><span>123</span></td></tr></table></body></html>