块级元素水平垂直居中
案例说明块级元素水平垂直居中利用css设置有三种方法,再把div(class='two')里面的spn内容水平垂直居中设置:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>块级元素水平垂直居中</title> <style> /*方法一*/ .one{ width: 200px; height: 200px; background-color: red; position: relative; } .two{ width: 100px; height: 100px; background-color: green; margin: auto; position: absolute; top: 0; bottom: 0; right: 0; left: 0; line-height: 100px; text-align: center; } /*方法二*/ .one{ width: 200px; height: 200px; background-color: red; display: table-cell; vertical-align: middle; text-align: center; } .two{ width: 100px; height: 100px; background-color: green; display: inline-block; line-height: 100px; } /*方法三*/ .one{ width: 200px; height: 200px; background-color: red; position: relative; } .two{ width: 100px; height: 100px; background-color: green; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; text-align: center; line-height: 100px; } </style> </head> <body> <div class="one"> <div class="two"><spn>文字居中</spn></div> </div> </body> </html>
注:方法2里面的 table-cell需要配合使用vertical-align
display: table-cell; 指的是:把元素会作为一个表格单元格显示
vertical-align: 设置元素的垂直对齐方式.属性值:
baseline 默认。元素放置在父元素的基线上。
sub 垂直对齐文本的下标。
super 垂直对齐文本的上标
top 把元素的顶端与行中最高元素的顶端对齐
text-top 把元素的顶端与父元素字体的顶端对齐
middle 把此元素放置在父元素的中部。
bottom 把元素的顶端与行中最低的元素的顶端对齐。
text-bottom 把元素的底端与父元素字体的底端对齐。
vertical-align: middle; 把此元素放置在父元素的中部