CSS - 设置div宽度100%和调整保持长宽比 [英] CSS - Set Div Width 100% and Resize Keeping Aspect Ratio

查看:135
本文介绍了CSS - 设置div宽度100%和调整保持长宽比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个背景图片,将覆盖部分头幻灯片的div。我想要div的宽度总是100%的窗口大小,即使当用户重新调整大小。高度应根据背景图像的宽高比而改变。背景图片的尺寸为1500x406。



以下是示例代码:



HTML

 < div id =wrapperclass =clearfix> 
< div id =bg_img>< / div>
< / div>



CSS
$ b

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



工作 JSFiddle

解决方案

您只需使用此代码

 < div id =some_div>< / div> 

#some_div:after {
content:;
display:block;
padding-top:100%; / * y超过x的百分比* /
}

它。 演示

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

N.B。





$ b

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


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆