个人 CSS 技能查漏补缺系列
关键在于 padding-top 和 padding-bottom 使用百分比(%)单位时是基于元素的 width 来计算的。
直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
   | <!DOCTYPE html> <html lang="en">     <head>         <meta charset="UTF-8" />         <meta http-equiv="X-UA-Compatible" content="IE=edge" />         <meta name="viewport" content="width=device-width, initial-scale=1.0" />         <title>Document</title>         <style>             @keyframes show {                 0% {                     width: 100px;                     height: 240px;                 }                 25% {                     width: 200px;                     height: 200px;                 }                 50% {                     width: 200px;                     height: 240px;                 }                 75% {                     width: 100px;                     height: 200px;                 }                 100% {                     width: 100px;                     height: 240px;                 }             }
              #wrapper {                 border: 1px solid black;                 animation: show 5s linear 0s infinite;             }
              #wrapper > #cube {                 --side: 80%;                 width: var(--side);                 padding: calc(var(--side) / 2) 0;                 background-color: blue;             }         </style>     </head>     <body>         <p>不管线框容器宽高怎么变,蓝色区块的宽高始终相等</p>         <div id="wrapper">             <div id="cube"></div>         </div>     </body> </html>
   |