Search code examples
javascripthtmlresizescalingaspect-ratio

How resize a div height based on width with pure JavaScript


while resizing div change height based on width with constraint ratio

@example div width:300 and height:600 next Ill change width to 400 height change to 800 based on width


Solution

  • You need to find the current width of the element and then reset its height.

    Here's a simple example of doing that. It is using offsetWidth to get the current width, but depending on your use case that may or may not be good enough. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

    Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after. If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.

    // Function to set the height of an element proportional to its width
    // el is the element we are interested in.
    // ratio is the ratio of width to height that we want
    function setHeight(el, ratio) {
    
    // first we need to find out what the width of el currently is
      const w = el.offsetWidth; //this will always return an integer
      console.log(w);
      el.style.height = (w * ratio) + 'px';
    
    //note you could also investigate getBoundingClientRect().width for a more general case when there have been transformations
    }
    <div class="element" style="width: 200px; height: 200px; background-color: magenta;" onclick="setHeight(this, 600/300);">Click me</div>

    offsetWidth always returns an integer, and of course there may have been some other calculations which make the width not an integer. Also what if there have been transformations? For a more comprehensive look at dimensions and what they mean see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect