自適應寬高的盒子中文本垂直水平居中

問題:如何讓span中的文字在div中垂直水平居中?

方法一:display:table;和display:table-cell;

給父元素div設置position: absolute;display:table;  這樣,div就會撐滿整個瀏覽器屏幕;

給需要居中的元素span設置display:table-cell; vertical-align:middle;  這樣,span就會撐滿div,span中的文字也在span中垂直居中,再用text-align: center;讓文字在span中水平居中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{
            margin: 0;
        }
        .father{
            width: 100%;
            height: 100%;
            background-color: yellow;
            position: absolute;
            display: table;
        }
        .son{
            background-color: lawngreen;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="father">
        <span class="son">我是測試文本</span>
    </div>
</body>
</html>

方法二、不用position: absolute;,而是給html,body設置顯性百分比100%。然後給父元素設置display:table,給需要居中的元素設置display:table-cell;vertical-align:middle;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{
            margin: 0;
            height: 100%;
        }
        .father{
            width: 100%;
            height: 100%;
            background-color: yellow;
            display: table;
        }
        .son{
            background-color: lawngreen;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="father">
        <span class="son">我是測試文本</span>
    </div>
</body>
</html>

方法三、彈性佈局flex

給需要其內容居中的元素div設置display:flex;justify-content:center;align-items:center;,這樣span在div中垂直水平居中,span是行內元素,文字撐滿了span,所以文字在div中也處於垂直水平居中。

如果span轉塊,有了寬高,那再給span設置display:flex;justify-content:center;align-items:center;讓文字在span中垂直水平居中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{
            margin: 0;
            height: 100%;
        }
        .father{
            width: 100%;
            height: 100%;
            background-color: yellow;
            display: flex;
            /*水平居中*/
            justify-content: center;
            /*垂直居中*/
            align-items: center;
        }
        .son{
            background-color: lawngreen;
        }
    </style>
</head>
<body>
<div class="father">
    <span class="son">我是測試文本</span>
</div>
</body>
</html>

 

小技巧tips:

設置高度、寬度百分比時,百分比是相對於父元素來確定,承接父元素的百分比是相對於瀏覽器屏幕大小來確定,必須給html,body設置顯性百分比100%。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章