简体   繁体   中英

How can I set the width of an element in CSS to be equal to 10% of the height?

I wanted my element to be a square. I wanted the side length of this element square to be 10% of the screen/window height. Yet, I don't know how to do that. Here's my code:

.Element {

width: /*How can I make the width equal to: [height: 10%]?*/;
height: 10%;
/*I wanted the element to be a square with a side length of [height: 10%].*/

}

You can use viewport-percentage lengths to get the effect that you want.

The vh unit length is based on 1% of the viewport/screen height, which I think is the one you wnat.

Alternatively, the vw unit length is based on 1% of the viewport/screen's width.

You can pick either one, just use the same length unit for both width and height .

Finally, you could also experiment with the vb and vi length units.

See: https://developer.mozilla.org/en-US/docs/Web/CSS/length

 .makeSquare { background-color: yellow; width: 10vh; height: 10vh; } 
 <div class="makeSquare"></div> <p>This is a square.</p> 

This should work

  .Element {
     width: 20vw;
     height: 20vw;
    }

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