固定宽度,高度设置为0或者不写, padding-bottom的值为 50%样式
如下:

  * {
        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;//垂直居中
      }
<div class="outer">
      <div class="inner">
        <div class="box">hello</div>
      </div>
    </div>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐