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

前端 未结 9 1131
面向向阳花
面向向阳花 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:54

    You can do it with the help of padding on a parent item, because relative padding (even height-wise) is based on the width of the parent element.

    CSS:

    .imageContainer {
        position: relative;
        width: 25%;
        padding-bottom: 25%;
        float: left;
        height: 0;
    }
    
    img {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
    }
    

    This is based on this article: Proportional scaling of responsive boxes using just CSS

提交回复
热议问题