How to place background image using ::before pseudo selectors in CSS ?
Given a web page and the task is to place the background image on web page using ::before pseudo selector.
The ::before pseudo selector is used to place something before the content of the selected items.
Syntax:
.container::before{
content: '';
background: url(image file);
position:absolute;
top:0px;
left:0px;
}Approach: The ::before pseudo selector places the background image before the selected element and if the selected element has a background color associated with it, we can use the z-index property to make the background image visible.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to place the background image using ::before pseudo selectors ? </title> <style> * { margin: 0px; padding: 0px; } body { text-align: center; } h1 { color: green; } .container { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; color: black; font-weight: bold; font-size: 2rem; } .container::before { content: ''; background: url('bg.png') no-repeat center center/cover; position: absolute; opacity: 0.3; top: 0px; left: 0px; width: 100vw; height: 100vh; z-index: -1; } span { font-size: 2em; } </style></head> <body> <div class="container"> GeeksforGeeks<br><br> How to place background image using ::before pseudo selectors ? </div></body> </html> |
Output:
Image Reference: https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200212230557/How-To-Become-A-Web-Developer-in-2020-A-Complete-Guide.png


.png)
.png)