DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Marius
Marius

Posted on

Preserve aspect ratio for images

I'm currently working on a website where I have images of random sizes. They all need to be responsive and be placed within a solid container that will maintain the aspect ratio of the image it contains. This can be done with the padding-top: x% and position:relative on parent element while the child (image) has position: absolute and top:0; left:0; right:0; bottom:0
So I found needed a way to calculate image radio based on dimensions. In my project I use chakra UI so, the radio has the form of a/b Let's look into it:

I'm using a API based CMS where I need to convert radios from strings into a/b format (not string)

// Transforms 'a/b' string into a/b
export const parseRatio = (prop: string) => {
  let newRatio = prop.split('/'),
      first = Number(newRatio[0]),
      second = Number(newRatio[1])
  return  first / second
}
Enter fullscreen mode Exit fullscreen mode

Next I found this neat little function that calculates my ratio based on image dimensions (that I can query from the API)

// compute ratio based on dimensions
export const ratioCalc = (w:number, h:number) => {
  let gcd :any = (a:number, b:number) => (b == 0) ? a : gcd (b, a%b),
    ratio = gcd(w, h),
    left = w/ratio,
    right = h/ratio
  return parseRatio(left + '/' + right)
}
Enter fullscreen mode Exit fullscreen mode

Let me know what you think.

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.