3

例如,当我在以下位置有图像时:

<img src="10px_image.png" alt="Some image" style="width: 100%" />

它的高度会根据图像的宽度自动缩放(例如,您可以在调整浏览器窗口大小时看到)。有没有办法对 html 中的其他元素做同样的事情?

4

2 回答 2

5

解决方案#1

您可以使用新的 css viewport unitsvwvh来实现这一点。

小提琴

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+

参考:w3cMozilla


解决方案#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;
}
于 2013-10-21T12:31:49.607 回答
0

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

于 2013-10-21T19:57:26.427 回答