1. 程式人生 > 實用技巧 >塊級元素水平垂直居中

塊級元素水平垂直居中

案例說明塊級元素水平垂直居中利用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; 把此元素放置在父元素的中部