2020前端面试-CSS篇

1.使盒子水平垂直居中

方式一:基于定位:

  • 绝对定位+边距:
.father {
     
        position: relative;
      }
      .son {
     
        width: 200px;
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
        background-color: orange;
      }
  • 绝对定位+CSS3移动:
.father {
     
        position: relative;
      }
      .son {
     
        width: 200px;
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: orange;
      }

  • 绝对定位+自动边距:
.father {
     
        position: relative;
      }
      .son {
     
        width: 200px;
        height: 200px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        background-color: orange;
      }

方式二:CSS3弹性布局

body {
     
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .son {
     
        width: 200px;
        height: 200px;
        background-color: orange;
      }

方式三:js方案

  .father {
     
        position: relative;
      }
      .son {
     
        width: 200px;
        height: 200px;
        background-color: lightcoral;
      }


 <script>
      let html = document.documentElement,
        fW = html.clientWidth,
        fH = html.clientHeight,
        sW = son.offsetWidth,
        sH = son.offsetHeight;
      son.style.position = "absolute";
      son.style.left = (fW - sW) / 2 + "px";
      son.style.top = (fH - sH) / 2 + "px";
    </script>

方案四:利用行内元素的特性

   .father {
     
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        /* 该种方式父元素必须设置宽高,且不能是百分比 */
        width: 500px;
        height: 500px;
      }
      .son {
     
        display: inline-block;
        width: 200px;
        height: 200px;
        background-color: lightsalmon;
      }

你可能感兴趣的:(前端开发)