CSS3小技巧-动态设定div的宽高比

前言

一直在写 vue 项目中使用 iview 的 table,它有个设置宽高固定的属性。于是我想在外层套一个 div 并且这个 div 动态的随着窗口大小调整,并且满足一定的宽高比,有这种需求是因为一个统计页面上有多个统计类型,其中就有表格。

  1. padding-bottom 实现普通元素固定宽高比,里 main 的元素获取父元素的全部宽高采用绝对布局 position:absolute;

    1
    2
    3
    <div class="wrapper">
    <div class="intrinsic-aspect-ratio-container"></div>
    </div>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    .wrapper {
    width: 40vw;
    }

    .intrinsic-aspect-ratio-container {
    width: 100%;

    height: 0;

    padding: 0;

    padding-bottom: 75%;

    margin: 50px;

    background-color: lightsalmon;
    }
  2. aspect-ratio 属性指定元素宽高比

    aspect-ratio 的语法格式如下:aspect-ratio: <width-ratio>/<height-ratio>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    /* 高度随动 */

    .box1 {
    width: 100%;

    height: auto;

    aspect-ratio: 16/9;
    }

    /* 宽度随动 */

    .box1 {
    width: auto;

    height: 100%;

    aspect-ratio: 16/9;
    }