我有一组元素,要求它们的最小宽度等于它们的高度,但高度没有明确设置。目前我可以通过设置 css 来实现这一点min-width
通过 jQuery 属性:
$(document).ready
(
function()
{
$('.myClass').each
(
function() {$(this).css('min-width', $(this).css('height'));}
);
}
);
是否可以直接在 css 中指定此行为?
这是一个 jsfiddle 演示了我想要实现的目标:http://jsfiddle.net/p8PeW/ http://jsfiddle.net/p8PeW/
其实不用JS也是可以的!
关键是要利用一个<img>
,这是一个被替换的元素 http://reference.sitepoint.com/css/replacedelements,因此,如果您仅设置高度,则会自动设置其宽度,以保留图像的固有纵横比。
因此您可以执行以下操作:
<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 的宽度设置为 133%.contents
将为高度的 133%.container
.
1:4长宽比的现场演示:https://jsbin.com/juduheq/edit https://jsbin.com/juduheq/edit(带有附加代码注释)。
另一个现场演示,其中容器的高度由同级元素中的文本量决定:https://jsbin.com/koyuxuh/edit https://jsbin.com/koyuxuh/edit
如果您想知道,img 数据 URI 用于1x1 像素透明 gif https://stackoverflow.com/questions/6018611/smallest-data-uri-image-possible-for-a-transparent-image)。如果图像的纵横比不是 1:1,则必须相应调整设置的高度值。您还可以使用<canvas>
or <svg>
元素而不是<img>
(谢谢Simo https://stackoverflow.com/questions/6148012/setting-element-width-based-on-height-via-css/14911949?noredirect=1#comment47749635_14911949).
如果您想设置元素height基于width,有一个更简单的技巧使用 CSS 保持 div 的纵横比 https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)