width和height的預設值auto與%詳解(附案例)。

2020-09-30 17:00:12

結論

  • width的%:定義基於包含塊(父元素)寬度的百分比寬度,會突破父級的限制

  • width的auto:儘量被父級包裹

  • height的%:基於包含它的塊級物件的百分比高度,會突破父級的限制

  • height的auto:儘量被父級包裹

案例

  • 一定複製程式碼跑一遍,花幾分鐘體會一下儘量被父級包裹與突破父級的限制

width案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        * {
            margin: 0;padding: 0;
        }
        body {
            background: #dcdcdc;
        }
        .box {
            width: 400px;
            border: 3px solid red;
            padding: 0 50px;
        }
        .box1 {
            width: auto;
            height: 100px;
            background: pink;
            padding: 0 50px;
            margin: 0 50px;
            border-width: 0 50px;
            border-style: solid;
            border-color: green;
        }
        .box2 {
            width: 100%;
            height: 100px;
            background: gold;
            padding: 0 50px;
            margin: 0 50px;
            border-width: 0 50px;
            border-style: solid;
            border-color: green;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="box1"></div>
    <div class="box2"></div>
</div>
</body>
</html>

height案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        * {
            margin: 0;padding: 0;
        }
        body {
            background: #dcdcdc;
        }
        .box {
            width: 400px;
            border: 3px solid red;
            padding: 50 0px;
            height: 400px;
        }
        .box1 {
            width: 200px;
            height:auto;
            background: pink;
            padding: 50px 0px;
            margin: 50px 0px;
            border-width: 50px 0px;
            border-style: solid;
            border-color: green;
        }
        .box2 {
            width: 200px;
            height:100%;
            background: gold;
            padding: 50px 0px;
            margin: 50px 0px;
            border-width: 50px 0px;
            border-style: solid;
            border-color: green;
        }
     
    </style>
</head>
<body>
<div class="box">
    <div class="box1"></div>
    <div class="box2"></div>
</div>
</body>
</html>