Created
March 13, 2017 00:48
-
-
Save drKnoxy/ceb8fa0ae00c86c86136007703b1df2b to your computer and use it in GitHub Desktop.
Responsive Image
This file contains 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 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