Can I scale a div's height proportionally to its width using CSS?

前端 未结 9 1140
面向向阳花
面向向阳花 2020-12-07 16:34

Can I set any variable in CSS like I want my div height to always be half of width my div scales with the screen size width for div is in percent

9条回答
  •  一个人的身影
    2020-12-07 16:53

    Another great way to accomplish this is to use a transparent image with a set aspect ratio. Then set the width of the image to 100% and the height to auto. That unfortunately will push down the original content of the container. So you need to wrap the original content in another div and position it absolutely to the top of the parent div.

    Content

    CSS

    .parent {
      position: relative;
    }
    .aspect-ratio {
      width: 100%;
      height: auto;
    }
    .content {
      position: absolute;
      width: 100%;
      top: 0; left: 0;
    }
    

提交回复
热议问题