问题描述
上面的指向可能重复项的链接在这种情况下不是解决方案,因为高度对于多个断点将是固定值.
我有一些带有 display:inline-block
的DIV,因此它们可以很好地并排漂浮.这些DIV都具有相同的高度,例如 height:300px
.稍后,我将使用Ajax将图像加载到每个DIV中,并且我希望DIV保持图像的长宽比,以便在实际加载图像时它们不会摆动.
I have some DIVs with display:inline-block
, so they are floating nicely side by side. These DIVs all have the same height, e.g. height:300px
. Later, I will load an image inside every DIV with Ajax, and I want the DIV to keep the aspect ratio of the image, so they won't wiggle all around, when the image is actually loaded.
因此,当DIV显示在浏览器中时,图像尚不存在,因此使用 height:auto;
固定图像的高度将不起作用.
So when the DIVs are displayed in the browser, the images are not yet there, so fixing the height for the image with height:auto;
won't work.
示例代码:
<div class="wrapper">
<div class="item">...</div>
<div class="item">...</div>
<!-- More items here -->
</div>
CSS:
.item {
display:inline-block;
vertical-align:top;
height: 300px;
width: /* depending on the image ratio */
}
现在,我知道如何保持给定宽度的元素的长宽比(请参见此处或此处).但是,由于我的DIV都应具有相同的高度,我如何才能保持宽高比并仅更改宽度?
Now I know how to keep the aspect ratio of an element for a given width (see here or here). But since my DIVs should all have the same height, how can I keep the aspect ratio and change just the width?
一种(不是很好)的解决方案是插入空白图像,然后将该图像调整为合适的尺寸.
One (not really good) solution would be to insert a blank image and to resize this image to the right dimensions.
问题是:调整窗口大小时,所有DIV的高度都会改变,因此仅计算宽度是不够的.我可以使用Javascript重新计算宽度,但我更喜欢普通的CSS版本(如果可能).
The problem is: when resizing the window, the height of all the DIVs will change, so just calculating the width is not enough. I could recalculate the width with Javascript, but I prefer a plain CSS version (if possible).
所以这是我的问题:如何仅通过CSS保持给定高度的元素的长宽比?
So here is my question: how can I keep the aspect ratio for an element for a given height by CSS only?
谢谢
推荐答案
您拥有宽高比,但没有实际的图像尺寸.我认为,您可以使用 calc
函数.浏览器支持仍然是一个问题:
You have the aspect ratio but not actual image dimensions. I think you can use the calc
function for this. Browser support is an issue though:
/* Note: using 30px height for demonstration */
.item {
display: inline-block;
vertical-align: top;
height: 30px;
background: #FC0;
}
.ratio-3-2 .item {
/* 3:2 = 1.5 */
width: calc(30px * 1.5);
}
.ratio-4-3 .item {
/* 4:3 = 1.3333 */
width: calc(30px * 1.3333);
}
<div class="wrapper ratio-3-2">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="wrapper ratio-4-3">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
在上面的演示中,第一组div的宽度为45px,第二组div的宽度为40px.
In the above demo, the first set of divs will be 45px wide and the second set will be 40px wide.
这篇关于CSS:在给定高度下保持元素的长宽比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!