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)