简体   繁体   中英

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).

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. 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 .

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. 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.

Just give the width and the height a value of 30vw

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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