根据最大宽度使用CSS按比例缩放div(类似于img缩放) [英] Proportionally scale a div with CSS based on max-width (similar to img scaling)
问题描述
是否可以仅使用CSS按比例缩放 div
,如 img
这是我的第一次尝试: http://dabblet.com/gist/1783363
示例
div {
max-width:100px;
max-height:50px;
}
img {
max-width:100px;
max-height:50px;
}
实际结果
容器:200 x 100
Div:100 x 50
图片:100 x 50
容器:50 x 100
Div:50 x 50 //我想这是50x25,像图片
图片:50 x 25
由于以百分比形式设置的垂直填充是根据元素的 width 计算的,因此我们可以使div总是具有特定的宽高比。 / p>
如果我们设置 padding-top:50% height:0
,div的高度总是其宽度的一半。
为了使文本出现在这样的容器中,你需要使它 position:relative
,并在里面放置另一个div,并将它定位在距离所有四边10px (您先设置的填充)。
请参阅我的代码段。
Is it possible to proportionally scale a div
like an img
using only CSS? Here is my first attempt: 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
Since vertical paddings set in percent are calculated out of width of an element we can make a div always be of a certain aspect ratio.
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:relative
and put another div inside it and position it absolutely 10px away from all four sides (the padding you set first).
See my fork of your code.
这篇关于根据最大宽度使用CSS按比例缩放div(类似于img缩放)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!