html - 像图像一样缩放元素

标签 html css

例如,当我有一张图片时:

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

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

最佳答案

解决方案#1

您可以使用新的 css 视口(viewport)单元 vwvh 等来完成此操作。

FIDDLE

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+

引用: w3c , mozilla


解决方案#2

FIDDLE

标记

<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/

相关文章:

html - 你如何在 css 的无序列表中添加 img 标签?

html - 你能相对或绝对定位显示中的元素吗 :table-cell?

jquery - 动态设置字符串截断

javascript - PNG 上的发光效果脉动发光效果

javascript - 更改 React 组件的 CSS 会影响所有其他页面

html - 如何在 CSS 中用垂直线分隔的字形和列列表?

jquery - html 选择下拉宽度太大

jquery - 使用CSS过渡从中心向左和向右扩展宽度

CSS 背景图像在某些浏览器上不是全尺寸

jquery - Shopify:当所选变体缺货时显示消息