Skip to content
Related Articles

Related Articles

How to place background image using ::before pseudo selectors in CSS ?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 14 Dec, 2020

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. 


    content: '';
    background: url(image file);

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.  



<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
        How to place the background image 
        using ::before pseudo selectors ?
        * {
            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;
    <div class="container">
        How to place background image using
        ::before pseudo selectors ?


Image Reference:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!