Code A Full Width Hero Background Image With Transparent Overlay
Build a full width background image with an overlay they said, it will be fun they said…
Hero images are a staple in modern web design & development, and at first glance, can seem like they are tricky to code with HTML & CSS yourself. However, I am here to spill the beans, and will show you that building something like this is in fact so easy, that my grandmother could do it!
In this article we will build this out in record time, and I will include screenshots throughout our progress! Once you are done, feel free to checkout the finished working example, and the YouTube video posted at the end of the article.
For best results, I recommend reading the article, and then checking out the video! You’ll be an HTML & CSS wizard by the end.
Let’s get started!
Choosing A Background Image For Our Hero
We will make this easy on ourselves, and grab a free HD photo from Unsplash. The image we will use is a beautiful picture of a forest.
Now that we have that, let’s start creating the basic HTML to get this photo on our web page.
Setting The Image As A Full Width Background Element
Our hero image is going to consist of only two HTML elements.
- A parent div that we will give a class of big-image.
- A child div that we will give a class of overlay.
It doesn’t matter what class names you give the elements, as long as they have the styling that I outline in the CSS section.
Here is all the HTML that we are going to need:
Styling Our Hero Image With CSS
Let’s style the big-image element first. All we really need to do here is set this element to be 100% of the height and width of the viewport, and then add a few background CSS properties.
Here is the CSS for that in all it’s glory.
With that in place, our hero image is already visible in the browser.
The last step is so simple, my grandmother is already done before we are! Let’s catch up to her.
Creating The Transparent Overlay
All we need to do here is create a div that will be 100% of the height and width of it’s parent element, which is .big-image in our case. We are going to make sure we also set the overlay div to be position absolute to ensure that it it will quite literally, lay over .big-image.
But any transparent overlay wouldn’t be complete without adding some color to it, so we need to see it’s background color, while making sure that we lower its opacity level. We can easily achieve that with an RGBA value.
To ensure that any text that we put inside of the hero image is nicely centered, we can easily add a few flexbox properties to achieve this.
Here is the final CSS for the .overlay div.
Tada! And there we have it ladies and gentlemen.