CSS - 设置 Div 宽度 100% 并调整大小保持纵横比 [英] CSS - Set Div Width 100% and Resize Keeping Aspect Ratio
问题描述
我有一个带有背景图像的 div,它将覆盖标题幻灯片的一部分.我希望 div 的宽度始终为窗口大小的 100%,即使用户重新调整大小也是如此.高度应根据背景图像的纵横比而变化.背景图片的尺寸为 1500x406.
示例代码如下:
HTML
<div id="bg_img"></div>
CSS
.clearfix {宽度:100%;位置:相对;显示:块;边距:0;填充:0;边框:0;行高:1.5;}#bg_img {背景: url('http://rndimg.com/ImageStore/OilPaintingBlue/999x400_OilPaintingBlue_19aa91c1b6e142f288fe69eb2a160a2b.jpg') 不重复;位置:绝对;z-索引:100;顶部:9em;宽度:100%;高度:406px;边距:0 自动;显示:内联;}
工作 JSFiddle
要使元素保持比例,您只需使用此代码
<div id="some_div"></div>#some_div:之后{内容: "";显示:块;填充顶部:100%;/* y 相对于 x 的百分比 */}
这就是实现它的方法.演示
<div id="bg_img"></div><div class="clearfix"></div>
注意此解决方案不需要 clearfix,OP 在他的代码中已经有了它.
CSS
#wrapper{位置:相对;宽度:100%;}#wrapper:之后{内容: "";显示:块;填充顶部:27.06666%;/* 406 超过 1500 */}#bg_img{位置:绝对;顶部:0;左:0;右:0;底部:0;背景:网址(http://placekitten.com/1500/406);背景尺寸:100% 100%;}
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-sizes it. The height should change based on the aspect ratio of the background image. The dimensions of the background image is 1500x406.
Here's the sample code:
HTML
<div id="wrapper" class="clearfix">
<div id="bg_img"></div>
</div>
CSS
.clearfix {
width: 100%;
position: relative;
display: block;
margin: 0;
padding: 0;
border: 0;
line-height: 1.5;
}
#bg_img {
background: url('http://rndimg.com/ImageStore/OilPaintingBlue/999x400_OilPaintingBlue_19aa91c1b6e142f288fe69eb2a160a2b.jpg') no-repeat;
position: absolute;
z-index: 100;
top: 9em;
width: 100%;
height: 406px;
margin: 0 auto;
display: inline;
}
The working JSFiddle
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%;
}
这篇关于CSS - 设置 Div 宽度 100% 并调整大小保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!