How to place background image using ::before pseudo selectors in CSS ?
Last Updated :
23 Jul, 2025
The ::before pseudo-element to place a background image in CSS means adding an image behind content by creating a virtual element before the main content. The ::before element is styled with background-image, content, and positioned with CSS, enhancing design flexibility.
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: Using ::before pseudo selectors
The ::before pseudo-selector adds a background image before the selected element. If the element has a background color, use the z-index property to position the image behind the content, making it visible.
Example: In this example we are using the ::before pseudo-element to add a background image behind the content in the .container. It positions the image with absolute, sets opacity, and uses z-index to layer it.
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(
'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200212230557/
How-To-Become-A-Web-Developer-in-2020-A-Complete-Guide.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: