fbpx
Skip to content Skip to sidebar Skip to footer

Get the Perfect Width-to-Height Ratio: A Guide to Div Sizing with CSS and JavaScript

Get The Perfect Width To Height Ratio A Guide To Div Sizing With Css And Javascript

You can set the width of a div based on its height using CSS. One way to do this is by using the aspect ratio feature, which allows you to set the width of an element based on its height. For example, if you want the div to have a width that is twice its height, you can use the following CSS:

 

div {
  width: 100%;
  height: 0;
  padding-bottom: 50%;
}
Alternatively, you can use the calc() function to set the width based on 



the height:

div { width: calc(100vh * 2); height: 100vh; } You can also use JavaScript to set the width based on the height:

var div = document.getElementById(“your-div-id”); div.style.width = div.offsetHeight * 2 + “px”; 

Note: vh unit is based on the height of the viewport, that means 1vh is equal to 1% of the viewport height.