[英]Auto Height of absolute Positioning in css
我想将图像设置为div中的背景,以便可以为每个设备更改源以获得图像分辨率。 问题是我不想设置div的高度,而只是它的宽度是100%,以便它可以适应设备窗口的宽度。 因此,我希望根据div的宽度自动生成高度。
我设置了auto的高度,但除非我用值设置高度,否则不显示div。
#imagetree {
position:absolute;
z-index:12;
width:100%;
height:auto;
bottom:0;
overflow: hidden;
background: url(images/trees.png);
background-repeat: no-repeat;
}
如果您事先知道图像的宽度和高度之间的比例,您可以使用比例padding-bottom
作弊
例如,如果您的图像是300x180
您可以使用此CSS
#imagetree {
position:absolute;
z-index:1;
bottom:0;
overflow: hidden;
background: url(http://dummyimage.com/300x180/000000/fff.jpg);
background-repeat: no-repeat;
width: 100%; /* use 100% of width */
padding-bottom: 60%; /* 180px is 60% of 300px */
background-size: cover; /* cover the div entirely with the background */
}
给定position: absolute
,最初不设置height
和width
。 您需要使用CSS手动设置它们。 在您的情况下,由于您已将背景作为图像,绝对定位,为什么要将其设置为background-image
?
您可以将图像放在<img />
标签中,然后使用与图像成比例的正常width
s和height
s进行渲染! 通过在absolute
定位容器内添加图像来更改代码。
<div id="imagetree">
<img src="images/trees.png" />
</div>
在CSS中,你可能想要这样:
#imagetree img {max-width: 100%;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.