通过 CSS 根据高度设置元素宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6148012/
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
Setting Element Width Based on Height Via CSS
提问by verdesmarald
I have a set of elements and require that their minimum width be equal to their height, but the height is not explicitly set. Currently I am able to achieve this by setting the css min-width
property via jQuery:
我有一组元素并要求它们的最小宽度等于它们的高度,但没有明确设置高度。目前,我可以min-width
通过 jQuery设置 css属性来实现这一点:
$(document).ready
(
function()
{
$('.myClass').each
(
function() {$(this).css('min-width', $(this).css('height'));}
);
}
);
Is it possible to specify this behaviour directly in the css?
是否可以直接在 css 中指定此行为?
Here is a jsfiddle demonstrating what I am trying to achieve: http://jsfiddle.net/p8PeW/
这是一个 jsfiddle,展示了我想要实现的目标:http: //jsfiddle.net/p8PeW/
采纳答案by Jeff
I don't believe this is possible without JS, but maybe someone can prove me wrong?
我不相信没有 JS 这是可能的,但也许有人可以证明我错了?
CSS doesn't allow you to use dynamic variables, so if the height isn't set until the page loads, I'm not sure how this could be done.
CSS 不允许您使用动态变量,因此如果在页面加载之前未设置高度,我不确定如何做到这一点。
回答by John Mellor
This is actually possible without JS!
这实际上没有 JS 是可能的!
The key is to make use of an <img>
, which is a replaced element, and hence if you only set the height, it's width will be automatically set in order to preserve the intrinsic aspect ratio of the image.
关键是要使用 an <img>
,它是一个替换元素,因此如果您只设置高度,它的宽度将自动设置以保留图像的固有纵横比。
Hence you can do the following:
因此,您可以执行以下操作:
<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>
If you wanted .contents
to have a 4:3 aspect ratio, then you would instead set the height of the img to 133%, so the width of the img and hence of .contents
would be 133% of the height of .container
.
如果您想要.contents
4:3 的纵横比,那么您可以将 img 的高度设置为 133%,因此 img 的宽度以及 of.contents
将是.img高度的 133% .container
。
Live demo of 1:4 aspect ratio: https://jsbin.com/juduheq/edit(with additional code comments).
1:4 纵横比的现场演示:https: //jsbin.com/juduheq/edit(附加代码注释)。
Another live demo, where the height of the container is determined by the amount of text in a sibling element: https://jsbin.com/koyuxuh/edit
另一个现场演示,其中容器的高度由同级元素中的文本量决定:https: //jsbin.com/koyuxuh/edit
In case you're wondering, the img data URI is for a 1x1 px transparent gif). If the image didn't have a 1:1 aspect ratio, you'd have to adjust the height values you set correspondingly. You could also use a <canvas>
or <svg>
element instead of the <img>
(thanks Simo).
如果您想知道,img 数据 URI 用于1x1 px 透明 gif)。如果图像没有 1:1 的纵横比,则必须相应地调整您设置的高度值。您也可以使用<canvas>
or<svg>
元素代替<img>
(感谢Simo)。
If instead you want to set element heightbased on width, there's a much easier trick at Maintain the aspect ratio of a div with CSS.
相反,如果您想根据width设置元素高度,则使用 CSS 保持 div 的纵横比有一个更简单的技巧。
回答by Henry Mazza
From W3C Box Modelon padding:
来自 W3C Box Modelon padding:
The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.
百分比是根据生成的框的包含块的宽度计算的,即使对于“padding-top”和“padding-bottom”也是如此。如果包含块的宽度取决于此元素,则生成的布局在 CSS 2.1 中未定义。
So you can have it using only CSS. See this examplefrom this blog poston another subject equally interesting. The trick to creating ratio boxes is using something like
所以你可以只使用 CSS。见这个例子从这个博客帖子上的另一个问题同样有趣。创建比例框的技巧是使用类似的东西
element::before {
content: '';
display: block;
padding-bottom: 100%;
}
回答by Simon
There is another very simple css solution but only for the exact case the OP presented in his jsfiddle:
还有另一个非常简单的css解决方案,但仅适用于OP在他的jsfiddle中提出的确切情况:
label {
background-color: Black;
color: White;
padding: 1px;
font-family: sans-serif;
text-align: center;
vertical-align: middle;
display: inline-block;
min-width: 1em; /* set width to the glyphs height */
}
<label>A</label><br/>
<label>B</label><br/>
<label>C</label><br/>
<label>D</label><br/>
<label>E</label><br/>
<label>F</label><br/>
<label>R6a</label>
回答by Pandaiolo
I had the same requirement and I use @John Melor solution with good success... until it did not work on Firefox. I tried reproducing my specific issue by testing the different jsbin code examples here, but no luck. Probably a highly specific browser bug based on my actual DOM. If someone has a jsbin of that issue, please share!
我有同样的要求,我使用 @John Melor 解决方案取得了成功......直到它在 Firefox 上不起作用。我尝试通过在这里测试不同的 jsbin 代码示例来重现我的特定问题,但没有成功。可能是基于我的实际 DOM 的高度特定的浏览器错误。如果有人有这个问题的jsbin,请分享!
I tried many combinations that all fail on the same thing: the container will not expand to the image width. Firefox declare that image has the width of its height, but the parent is 1px width no matter what I tried.
我尝试了许多组合,但在同一件事上都失败了:容器不会扩展到图像宽度。Firefox 声明图像具有其高度的宽度,但无论我尝试什么,父级都是 1px 宽度。
For whomever find himself in that situation, I used a js bugfix that stays local to the image element. If the height of the container isn't specified like in the initial OP question, that could also be useful to you.
对于任何发现自己处于这种情况的人,我使用了一个 js 错误修复,它保持在图像元素的本地。如果没有像初始 OP 问题中那样指定容器的高度,这对您也可能有用。
In JSX/ES6:
在 JSX/ES6 中:
const TRANSPARENT_PIXEL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
const setWidthToHeight = e => { e.target.style.width = e.target.height }
const force1x1Ratio = <img src={TRANSPARENT_PIXEL} onLoad={setWidthToHeight} />
With plain ol' HTML
使用简单的 ol' HTML
<img
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
onLoad="javascript:function(e) { e.target.style.width = e.target.height + 'px' }" />
回答by Blender
If you are trying to make squares, you'll have to account for both cases (W > H
and W < H
):
如果您要制作正方形,则必须考虑两种情况(W > H
和W < H
):
$('label').each(function() {
if ($(this).height() > $(this).width()) {
$(this).css('min-width', $(this).height());
} else {
$(this).css('min-height', $(this).width());
}
});