Maintain div aspect ratio according to height

前端 未结 5 2045
日久生厌
日久生厌 2020-11-28 12:05

I need to maintain the width of an element as a percentage of its height. So as the height changes, the width is updated.

The oppo

5条回答
  •  心在旅途
    2020-11-28 12:30

    You can use an image that has the desired proportions as to help with proportional sizing (images can be scaled proportionally by setting one dimension to some value and other to auto). The image does not have to be visible, but it must occupy space.

    .box {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 50%;
    }
    .size-helper {
      display: block;
      width: auto;
      height: 100%;
    }
    .inner {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(255, 255, 153, .8);
    }
    1. box has fluid height
    2. img has 2:1 aspect ratio, 100% height, auto width, static position
    2.1 it thus maintains width = 200% of height
    2.2 it defines the dimensions of the box
    3. inner expands as much as box

    In the above example, box, inner and helper are all same size.

提交回复
热议问题