例如,当我在以下位置有图像时:
<img src="10px_image.png" alt="Some image" style="width: 100%" />
它的高度会根据图像的宽度自动缩放(例如,您可以在调整浏览器窗口大小时看到)。有没有办法对 html 中的其他元素做同样的事情?
您可以使用新的 css viewport unitsvw
等vh
来实现这一点。
div
{
width: 40vw;
height: 20vw;
background: pink;
}
CSS3 有一些相对于当前视口大小调整事物大小的新值:vw、vh 和 vmin。三个值中任何一个的一个单位是视口轴的 1%。“视口” == 浏览器窗口大小 == 窗口对象。如果视口为 40 厘米宽,则 1vw == 0.4 厘米。
1vw = 视口宽度的 1% 1vh = 视口高度的 1% 1vmin = 1vw 或 1vh,以较小者为准 1vmax = 1vw 或 1vh,以较大者为准(css-tricks 帖子)
支持:IE 9+、Firefox 19+、Chrome 20+、Safari 6+
<div class="container">
<div class="outer r4x3">
<div class="inner">
</div>
</div>
</div>
/* container defines margins and width */
.container {
margin: 60px 120px 0;
}
/* outer container will define aspect ratio */
.outer {
position: relative;
width: 100%;
}
.outer.r4x3 {
padding-top: 75%; /* "height" will be 3/4 of width */
}
/* inner container positioned absolutely and holds content */
.outer .inner {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
outline: 1px solid grey;
background: pink;
}
here is a trick which is actually for responsive video and Iframes to maintain aspect ratio but it work on other things as well... http://webdesignerwall.com/tutorials/css-elastic-videos