DEV Community

Marius
Marius

Posted on

2 2

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay