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

时间秒杀一切 提交于 2019-12-02 04:06:47

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

<div id="some_div"></div>

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

So this is how to achieve it. Demo

<div id="wrapper">
    <div id="bg_img"></div>
</div>
<div class="clearfix"></div> 

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%;
}

This is what I've used in the past to support back to IE8. Used in conjunction with a small js plugin here that supports the filters: http://louisremi.github.io/jquery.backgroundSize.js/demo/

img {
-webkit-background-size:cover;
-moz-background-size:cover;
background-size:cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='cover');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='cover')";}
background-position:50% 0;
}

I found a solution which is simple and works great for me. Create a transparent PNG for the aspect ratio you desire, e.g. 15px x 4px.

put the image within the div. Set the image's width to 100%. It will expand to the div's width and grow in the proper aspect ratio vertically, pushing the div's height down to the proper aspect ratio.

Something like this (this exact sample untested):

<div style="width: 100%">
 <img src="..." style="width: 100%" />
</div>

You could, of course, do this with the other dimension (height) as well by defining it instead of width.

Simple enough. Works for me.

-- Andrew

This somewhat distorts the image, but it might be what you are looking for:

#bg_img {
    background: url('http://rndimg.com/ImageStore/OilPaintingBlue/999x400_OilPaintingBlue_19aa91c1b6e142f288fe69eb2a160a2b.jpg') no-repeat;
min-width:100%;
min-height:100%;
background-size:cover;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!