Scaling elements proportionally using CSS and JQUERY3

Scaling elements proportionally using CSS and JQUERY3 is a fairly straightforward task. In order to achieve this, we can use CSS flexbox or the standard CSS transform property. Using flexbox, we can set the parent element to display: flex and then use the flex-grow property of its children elements. For example, if we want to scale the child elements to a certain size proportionally, we can set the flex-grow value to the ratio we want.

<div class="parent" style="display: flex">
    <div class="child" style="flex-grow: 0.5"></div>
    <div class="child" style="flex-grow: 0.5"></div>

In the example above, we set the flex-grow value of the two child elements to 0.5 which means that they will scale to half the size of the parent element. We can also use the standard CSS transform property to scale elements proportionally. The syntax for this would be:

transform: scale(x, y);

Where the x and y are the ratios we want to scale the element to. So if we wanted to scale the element to half its size, we could use the following:

transform: scale(0.5, 0.5);

Finally, if we wanted to do this dynamically with JQuery3, we could use the following code:

  var ratio = $(this).attr('data-ratio');
  $(this).css('transform', 'scale(' + ratio + ',' + ratio + ')');

In this example, we iterate over all the children elements of the parent, get their ratio value from the data-ratio attribute and then set the transform property using the scale value we got.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]