我有一组元素,要求它们的最小宽度等于它们的高度,但高度没有明确设置。目前我可以通过 jQuery 设置 css min-width
属性来实现这一点:
$(document).ready
(
function()
{
$('.myClass').each
(
function() {$(this).css('min-width', $(this).css('height'));}
);
}
);
是否可以直接在 css 中指定此行为?
这里有一个 jsfiddle 演示了我正在努力实现的目标:http://jsfiddle.net/p8PeW/
最佳答案
这实际上可以不用 JS!
关键是利用 <img>
,这是一个 replaced element ,因此如果您只设置高度,它的宽度将自动设置,以保持图像的固有纵横比。
因此您可以执行以下操作:
<style>
.container {
position: relative;
display: inline-block; /* shrink wrap */
height: 50vh; /* arbitrary input height; adjust this */
}
.container > img {
height: 100%; /* make the img's width 100% of the height of .container */
}
.contents {
/* match size of .container, without influencing it */
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<div class="container">
<!-- transparent image with 1:1 intrinsic aspect ratio -->
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
<div class="contents">
Put contents here.
</div>
</div>
如果你想要.contents
要有 4:3 的纵横比,那么您可以将 img 的高度设置为 133%,因此 img 的宽度和 .contents
的宽度将是 .container
高度的 133% .
1:4 宽高比的现场演示:https://jsbin.com/juduheq/edit (带有额外的代码注释)。
另一个现场演示,其中容器的高度由同级元素中的文本数量决定:https://jsbin.com/koyuxuh/edit
如果您想知道,img 数据 URI 是针对 1x1 px transparent gif 的).如果图像的纵横比不是 1:1,则必须相应地调整设置的高度值。你也可以使用 <canvas>
或 <svg>
元素而不是 <img>
(感谢 Simo)。
如果您想根据宽度 设置元素高度,在Maintain the aspect ratio of a div with CSS 有一个更简单的技巧。 .
关于css - 通过 CSS 根据高度设置元素宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58096736/