Skip to content

Instantly share code, notes, and snippets.

@drKnoxy
Created March 13, 2017 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drKnoxy/ceb8fa0ae00c86c86136007703b1df2b to your computer and use it in GitHub Desktop.
Save drKnoxy/ceb8fa0ae00c86c86136007703b1df2b to your computer and use it in GitHub Desktop.
Responsive Image
import React from 'react';
import styled from 'styled-components';
/**
* @param {string} src
* @param {string} alt
* @param {number} width Some ratio you like
* (Math.sqrt(5) + 1) / 2 : Golden Ratio
* 16/9 : Widescreen
* 2.414 : Ultra wide
*/
const HeroImage = (
{ width = 2.414, children = false, style = {}, alt = '', ...rest }
) => {
const ratio = Math.pow(width, -1) * 100;
const Img = styled.div`
position: relative;
width: 100%;
font-size: 0;
line-height: 0;
vertical-align: middle;
background-size: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-image: url(${props => props.src});
`;
const Spacer = styled.div`
display: block;
height: 0;
padding-top: ${ratio}%;
`;
return (
<Img {...rest} ariaRole="image" ariaLabel={alt}>
<Spacer />
</Img>
);
};
export default HeroImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment