Last active
June 12, 2019 00:08
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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