Hey guys, this is my first blog post and it's about how to set the opacity of your background image using CSS. I am an attendee of the hashnode bootcamp II and during the first session we were given a task to 'create an article that would help our past self solve a problem we've encountered before'. I had trouble coming to a conclusion on what to write about as one part of me wanted to talk about how I overcame several jinxes before I could start my journey into the developer world. After writing several drafts from the different ideas I had, I finally decided to publish one of the drafts: this one.
One challenge people encounter is setting the opacity of their background images, either to enhance the contrast with page text or for another reason. While working on my first portfolio, I also encountered this problem and after several trials and errors and with suggestions online, I came across a solution which works for me and I've decided to share it. This solution involves the use of the CSS selector '::after'. Enjoy!!!
The first thing to do is to set a container in the body of your html. Set the container to any size (for example 95%) relative to the width of the body with a maximum width of 100% the width of the viewport. Set the margin to '0 and auto' to center your container vertically.
.container {
width: 95%;
max-width: 100vw;
margin: 0 auto;
}
The next step is to use the css selector '::after' to set the background image.
.container::after {
content: "";
background: url("sampleImage.jpg");
}
That being done, you can now set the opacity of the background image:
opacity: 0.x;
To ensure that the image always stays in one position on the page, you use the fixed positioning property of css:
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
Finally, to ensure that the background image stays at the bottom of everything else, you use the 'z-index' feature provided by css. Based on the fact that the higher the z-index, the higher the position of the object on the screen, we give it a negative value to ensure that it is always at the bottom of the page:
z-index: -1;
The final code will take something of this form:
.container::after {
content: "";
background: url("sampleImage.jpg");
opacity: 0.x;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
With this, you can set any background image you want for your page and give it any opacity you want to improve contrast on the page for readers or for whatever reason you need.
Thank you for reading. I'd really appreciate if you can leave feedbacks and suggestions for me in the comment box.