例如,当我有一张图片时:
<img src="10px_image.png" alt="Some image" style="width: 100%" />
它的高度会根据图像的宽度自动缩放(例如,您可以在调整浏览器窗口大小时看到这一点)。有没有办法对 html 中的其他元素做同样的事情?
最佳答案
解决方案#1
您可以使用新的 css 视口(viewport)单元 vw
、vh
等来完成此操作。
div
{
width: 40vw;
height: 20vw;
background: pink;
}
CSS3 has some new values for sizing things relative to the current viewport size: vw, vh, and vmin. One unit on any of the three values is 1% of the viewport axis. "Viewport" == browser window size == window object. If the viewport is 40cm wide, 1vw == 0.4cm.
1vw = 1% of viewport width 1vh = 1% of viewport height 1vmin = 1vw or 1vh, whichever is smaller 1vmax = 1vw or 1vh, whichever is larger (css-tricks post)
Support : IE 9+, Firefox 19+, Chrome 20+, Safari 6+
解决方案#2
标记
<div class="container">
<div class="outer r4x3">
<div class="inner">
</div>
</div>
</div>
CSS
/* 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;
}
关于html - 像图像一样缩放元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19493803/