Today I learnt how to add a responsive background image using grid.
People use grid to create responsive layouts, but did you know you can use it to add a responsive background image as well?
Consider the following html code:
By turning the body into a grid container, we can position the .background and .hero elements on top of each other.
As shown in the css below:
body {
display: grid;
grid-template-rows: 1fr 1fr;
grid-template-columns: 1fr 1fr;
}
.background {
grid-row: 1 / 3;
grid-column: 1 / 3;
}
.hero {
grid-row: 1 / 3;
grid-column: 1 / 3;
}
I mostly use this technique to have more control over the size and position of the background image.
Here's the codepen example:
https://codepen.io/wintersunset95/full/zYbrVQJ