Maintain div aspect ratio according to height

前端 未结 5 2038
日久生厌
日久生厌 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

    I can't find a pure CSS solution. Here's a solution using CSS Element Queries JavaScript library.

    var aspectRatio = 16/9;
    var element = document.querySelector('.center');
    function update() {
      element.style.width = (element.clientHeight * aspectRatio) + 'px';
    }
    
    new ResizeSensor(element, update);
    update();
    

    CodePen demo!

提交回复
热议问题