前端面试 CSS— 实现布局:div垂直居中,左右10px,高度始终为宽度一半

Posted aiguangyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端面试 CSS— 实现布局:div垂直居中,左右10px,高度始终为宽度一半相关的知识,希望对你有一定的参考价值。

实现一个div垂直居中, 其距离屏幕左右两边各10px, 其高度始终是宽度的50%,同时div 中有一个文字A,文字需要水平垂直居中。

这个问题咋一看,面试官有点瞧不起人啊,出这种简单的题,实际面试官想要考察的是:padding-bottom 的值为百分比时,究竟是相对于谁的值?  这里直接给出答案:padding-top、padding-bottom、margin-top、margin-bottom 属性设置为百分比时,参考对象都是父级元素的宽度。

以下是代码实现,大家可以直接复制粘贴进行验证:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <style>
    * {
      margin: 0;
      padding: 0;
    }

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

    .outer-box {
      margin: 0 10px;
      height: 100%;
      display: flex;
      align-items: center;
    }

    .inner-box {
      background: red;
      position: relative;
      width: 100%;
      /* 这个是精华和重点 */
      padding-bottom: 50%;
    }

    .box {
      position: absolute;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 20px;
    }
  </style>
</head>

<body>
  <div class="outer-box">
    <div class="inner-box">
      <div class="box">A</div>
    </div>
  </div>
</body>

</html>

当然,这个面试题也可以用计算属性来实现,但是那样的你可能得不到面试官的青睐,以下是代码实现。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <style>
    * {
      padding: 0;
      margin: 0;
    }

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

    .wrapper {
      position: relative;
      width: 100%;
      height: 100%;
    }

    .box {
      margin-left: 10px;
      /* vw是视口的宽度, 1vw代表1%的视口宽度 */
      width: calc(100vw - 20px);
      /* 宽度的一半 */
      height: calc(50vw - 10px);
      position: absolute;
      background: red;
      /* 让块垂直居中 */
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
    }
  </style>
</head>

<body>
  <div class="wrapper">
    <div class="box">A</div>
  </div>
</body>

</html>

以上是关于前端面试 CSS— 实现布局:div垂直居中,左右10px,高度始终为宽度一半的主要内容,如果未能解决你的问题,请参考以下文章

2019前端面试系列——CSS面试题

HTML CSS中如何实现DIV中的图片水平垂直居中对齐

前端面试题前端布局问题

使用CSS实现div居中布局:

前端面试题CSS

前端最强面试宝典 - CSS 篇