Html 根据 max-width 使用 CSS 按比例缩放 div(类似于 img 缩放)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9219005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:25:43  来源:igfitidea点击:

Proportionally scale a div with CSS based on max-width (similar to img scaling)

imagehtmlcssscale

提问by Adam Youngers

Is it possible to proportionally scale a divlike an imgusing only CSS? Here is my first attempt: http://dabblet.com/gist/1783363

是否可以divimg只使用 CSS那样按比例缩放?这是我的第一次尝试:http: //dabblet.com/gist/1783363

Example

例子

div {
 max-width:100px;
 max-height:50px;
}
img {
 max-width:100px;
 max-height:50px;
}

Actual Result

实际结果

Container: 200 x 100
Div:       100 x 50
Image:     100 x 50

Container: 50  x 100
Div:       50  x 50  // I want this to be 50x25, like the image
Image:     50  x 25

回答by Spadar Shut

Since vertical paddings set in percent are calculated out of widthof an element we can make a div always be of a certain aspect ratio.

由于以百分比设置的垂直填充是根据元素的宽度计算的,因此我们可以使 div 始终具有特定的纵横比。

If we set padding-top:50%; height:0, the height of the div will always be half of its width. And to make text appear inside such a container you need to make it position:relativeand put another div inside it and position it absolutely 10px away from all four sides (the padding you set first).

如果我们设置padding-top:50%; height:0,则 div 的高度将始终是其宽度的一半。并且要使文本出现在这样的容器中,您需要制作它position:relative并在其中放置另一个 div并将其放置在距离所有四个边(您首先设置的填充)绝对 10px 的位置。

See my fork of your code.

请参阅我的代码分支

回答by zim2411

Sort of. You could use transformations to scale it up, but I'm not sure that's what you have in mind.

有点。您可以使用转换来扩大规模,但我不确定这是您的想法。

-webkit-transform:scale(2);(and other prefixes) would double it in size, without altering page layout.

-webkit-transform:scale(2);(和其他前缀)会将其大小加倍,而不会改变页面布局。

回答by user3849374

Try:

尝试:

.container img {
    height:50vw;
}

The vw follows the viewport You need to set in the head of your document:

vw 遵循您需要在文档头部设置的视口:

<head>
<meta name="viewport" content="width=device-width">
</head>