Skip to content

Instantly share code, notes, and snippets.

@srph
Last active June 12, 2019 00:08
Show Gist options
  • Save srph/9ca7003894d66b4e108285b4ee2d7bd3 to your computer and use it in GitHub Desktop.
Save srph/9ca7003894d66b4e108285b4ee2d7bd3 to your computer and use it in GitHub Desktop.
React: Component to maintain an aspect ratio for an image (i.e., forget the hack)
import './style.css'
import * as React from 'react'
export type Props = React.ImgHTMLAttributes<HTMLImageElement> & {
ratio: number
}
function ImageAspectRatio(props: Props) {
const { ratio, ...imgProps } = props
return (
<div className="c-image-aspect-ratio" style={{ paddingBottom: `${ratio}%` }}>
<img {...imgProps} />
</div>
)
}
export default ImageAspectRatio
.c-image-aspect-ratio {
position: relative;
}
.c-image-aspect-ratio > img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: 100%;
width: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment