简体   繁体   English

宽度相对于高度的 100%

[英]Width 100% relative to height

So we can set the height of an element based on the element's width, like:所以我们可以根据元素的宽度来设置元素的高度,比如:

.box {
  width: 30vw;
  height: auto;
}

And it will present us with good dimensions (assuming the box is 30vw wide initially).它将为我们提供良好的尺寸(假设盒子最初是 30vw 宽)。

Is there any way we can do a reverse way, say:有没有办法我们可以做相反的事情,说:

.box {
  height: 30vh;
  width: auto;
} 

I suppose the box will just take the whole parent's width in this case, but can I change this behavior somehow so that it is relative to the element's height?我想在这种情况下,盒子只会占用整个父元素的宽度,但我能以某种方式改变这种行为,使其相对于元素的高度吗?

In this case在这种情况下

.box {
  width: 30vw;
  height: auto;
}

an element with class box will have width 30vw and its height will depend on the form of the element and its children.带有 class 框的元素的宽度为 30vw,其高度取决于元素及其子元素的形式。 For example, if an img element is given class box it will have 30vw width and its height will be the right size to preserve its aspect ratio which I think is what is meant in the question by present us with good dimensions .例如,如果给定一个 img 元素 class 框,它将具有 30vw 宽度,其高度将是保持其纵横比的正确大小,我认为这就是问题中present us with good dimensions的意思。

In the second case在第二种情况下

.box {
  height: 30vh;
  width: auto;
} 

if an img element is given class box then its height will be 30vh and its width will be set so that it maintains its aspect ratio.如果给定一个 img 元素 class 框,那么它的高度将为 30vh,其宽度将被设置为保持其纵横比。 It will not take the width of the parent as the question supposes and in fact will do as the question wants and have a width calculated in relation to the specified height.它不会像问题假设的那样采用父级的宽度,实际上会按照问题的要求进行操作,并根据指定的高度计算宽度。

In the case of a div given class box and some text contained in it the height will be as specified and the text, if not further styled, will take up the width of the parent element.在给定 class 框和其中包含的一些文本的 div 的情况下,高度将如指定的那样,如果不进一步设置样式,文本将占据父元素的宽度。

Just give the width and the height a value of 30vw只要给宽度和高度一个值 30vw

 .box{ background: #33ee55; height: 30vw; width: 30vw; }
 <div class='box'></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM