table-cell設置寬高、居中


  • table-cell默認寬高由內容決定
    <style type="text/css" rel="stylesheet">
        .content {
            color: white;
        }
        
        .cell {
            background-color: blue;
            display: table-cell;
        }
    </style>

    <div class="content">
        <div class="cell">
            test
        </div>
    </div>

  • 可以設置固定寬高:
 .cell {
            background-color: blue;
            display: table-cell;
            width: 100px;
            height: 100px;
        }
  • 直接設置寬高百分比是無效的,因為table沒有顯式聲明,默認加的table寬高也是由內容決定,所有要使用百分比,必須顯式聲明table並定義寬高(row默認充滿table)
<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title>cell</title>
</head>

<body>

    <style type="text/css" rel="stylesheet">
        .content {
            color: white;
        }
        
        .table {
            display: table;
            width: 100%;
            height: 200px;
        }
        
        .cell {
            background-color: blue;
            display: table-cell;
            width: 100%;
            height: 100%;
        }
    </style>
    <div class="content">
        <div class="table">
            <div class="cell">
                test
            </div>
        </div>

    </div>
</body>

</html>
  • cell里的內容水平居中
.cell {
            background-color: blue;
            display: table-cell;
            width: 100%;
            height: 100%;
            text-align: center;
        }
  • cell里的內容垂直居中:
 .cell {
            background-color: blue;
            display: table-cell;
            width: 100%;
            height: 100%;
            text-align: center;
            vertical-align: middle;
        }

注意:設置 line-height: 100%;無效,無法讓文字垂直居中,設置 line-height: 200px;也可以垂直居中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM