CSS - Set Div Width 100% and Resize Keeping Aspect Ratio

后端 未结 4 985
天命终不由人
天命终不由人 2021-01-24 05:03

I have a div with a background image that will overlay part of the header slideshow. I want the width of the div to always be 100% of the window size, even when the user re-size

4条回答
  •  不思量自难忘°
    2021-01-24 05:42

    To make an element maintain proportions you only have to use this code

    #some_div:after{ content: ""; display: block; padding-top: 100%; /* the percentage of y over x */ }

    So this is how to achieve it. Demo

    N.B. clearfix isn't required for this solution, OP had it in his code.

    CSS

    #wrapper{
        position: relative;
        width: 100%;
    }
    #wrapper:after{
        content: "";
        display: block;
        padding-top: 27.06666%; /* 406 over 1500  */
    }
    #bg_img{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url(http://placekitten.com/1500/406);
        background-size: 100% 100%;
    }
    

提交回复
热议问题