我有一个带有背景图像的div,我想扩展100%的宽度并自动缩放div以适应所需的图像高度。目前,它并不是缩放div高度,除非我将div的高度设置为100%,但是它只是延伸到屏幕的全部高度,而我希望它能够缩放到图像的高度。
以下是html:
<div id="mainHeaderWrapper">
</div><!--end mainHeaderWrapper-->
<br class="clear" />;下面是css:
#mainHeaderWrapper{
background: url(http://localhost/site/gallery/bg1.jpg);
width: 100%;
height: auto;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-size: 100% 100%;
background-repeat: no-repeat;
background-position: center center;
}
.clear { clear: both; }谢谢你的帮助
发布于 2015-05-04 16:56:21
让一个透明的图像指定DIV维数。
在该div内部,使用CSS opacity: 0放置相同的图像。
<div id="mainHeaderWrapper">
<img src="path/to/image.jpg"><!-- I'm invisible! -->
</div>将图像设置为
#mainHeaderWrapper {
background: no-repeat url(path/to/image.jpg) 50% / 100%;
}
#mainHeaderWrapper img {
vertical-align: top;
width: 100%; /* max width */
opacity: 0; /* make it transparent */
}这样,DIV的高度将由包含的不可见图像决定,并且将background-image设置为中心,full (50% / 100%)它将与该图像的比例相匹配。
需要在DIV里面放些内容吗?
由于包含图像,您将需要一个额外的子元素,该元素将被设置为position: absolute ,充当一个覆盖元素
<div id="mainHeaderWrapper">
<img src="path/to/image.jpg"><!-- I'm invisible! -->
<div>Some content...</div>
</div>#mainHeaderWrapper{
position: relative;
background: no-repeat url(path/to/image.jpg) 50% / 100%;
}
#mainHeaderWrapper > img{
vertical-align: top;
width: 100%; /* max width */
opacity: 0; /* make it transparent */
}
#mainHeaderWrapper > div{
position: absolute;
top: 0;
width: 100%;
height: 100%;
}发布于 2015-05-04 17:03:13
如果您知道图像的比例,请使用百分比填充来定义容器的高度。设置height:0并将垂直填充设置为宽度的百分比。
这种方法的关键是基于百分比的垂直填充总是与宽度相关的。
该百分比是根据生成的框的包含块的宽度计算的,甚至对于“填充-顶”和“填充-底部”也是如此。
下面,图像为400 set 200 50,高宽比为1:2,padding-top设置为50%;
#mainHeaderWrapper {
width: 100%;
height: 0;
padding-top: 50%;
background-image: url('https://dummyimage.com/400x200/');
background-size: 100% auto;
background-repeat: no-repeat;
}<div id="mainHeaderWrapper"></div>
stuff below the image
在另一个例子中,图像是300 pxX100px。高度为宽度的⅓,因此将⅓设置为33.33%:
#mainHeaderWrapper {
width: 100%;
height: 0;
padding-top:33.33%;
background-image: url('https://dummyimage.com/300x100/');
background-size: 100% auto;
background-repeat: no-repeat;
}<div id="mainHeaderWrapper"></div>
stuff below the image
编辑:
正如Paulie_D提示的那样,div中的其他内容必须绝对定位,如下所示。我建议使用百分比来定位这些元素。
#mainHeaderWrapper {
width: 100%;
height: 0;
padding-top: 33.33%;
background-image: url('https://dummyimage.com/300x100/');
background-size: 100% auto;
background-repeat: no-repeat;
}
div#inner_content {
position: absolute;
top: 0;
width: 100%;
margin-top: 10%;
color: #FFF;
text-align: center;
font-size: 20px;
}<div id="mainHeaderWrapper">
<div id="inner_content">Hello World</div>
</div>
stuff below the image
发布于 2017-09-17 22:23:06
这可以不使用虚拟图像来完成。例如,我将使用刚处理过的图像的维数。
我的图像尺寸是2880x1410。简化尺寸-> 96/47 (我使用了这个简单的比率计算器比率/)。一旦得到简化的比率,将高度和宽度插入方程:
高度:calc((100 96* W) / H);因此,我的:高度:calc((100 96* 47) / 96);
也不必担心div的内容(除非它们不合适)。
https://stackoverflow.com/questions/30035530
复制相似问题