经典css面试题

css div 垂直水平居中,并完成 div 高度永远是宽度的一半(宽度可以不指定)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      html,
      body {
        width: 100%;
        height: 100%;
      }

      .outer {
        width: 400px;
        height: 100%;
        background: blue;
        margin: 0 auto;

        display: flex;
        align-items: center;
      }

      .inner {
        position: relative;
        width: 100%;
        height: 0;
        padding-bottom: 50%;
        background: red;
      }

      .box {
        position: absolute;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    </style>
  </head>
  <body>
    <div class="outer">
      <div class="inner">
        <div class="box">hello</div>
      </div>
    </div>
  </body>
</html>

实现一个大小为父元素宽度一半的正方形

.outer {
   width: 400px;
   height: 600px;
   background: red;
}
.inner {
   width: 50%;
   padding-bottom: 50%;
   background: blue;
}

CSS实现自适应正方形、等宽高比矩形

a.双重嵌套,子绝父相
.outer {
   padding-top: 50%;
   height: 0;
   background: #ccc;
   width: 50%;
   position: relative;
}
.inner {
   position: absolute;
   width: 100%;
   height: 100%;
   top: 0;
   left: 0;
   background: blue;
}
b.padding撑高画正方形
.outer {
   width: 400px;
   height: 600px;
   background: blue;
}
.inner {
   width: 100%;
   height: 0;
   padding-bottom: 100%;
   background: red;
}
c.相对于视口VW VH
.inner {
   width: 1vw;
   height: 1vw;
   background: blue;
}
d.伪元素设置margin-top
.inner {
   width: 100px;
   overflow: hidden;
   background: blue;
}
.inner::after {
   content: "";
   margin-top: 100%;
   display: block;
}

实现两栏布局

上一篇:封神台靶场:萌新也能找CMS突破


下一篇:弹性盒子模型之flex属性总结