Place Background Image Using Before Pseudo Selectors in CSS



To Place background image using ::before pseudo selectors, we will be using background-image and ::before psuedo element. CSS ::before pseudo-element is used to add content before the selected element with the content property allowing to insert text, images, or decorative elements, without modifying the HTML structure.

In this article, we are going to place background image using ::before pseudo selector inside a div element.

Placing background image using ::before pseudo selectors

  • We have used a div element with class name as background where image will be used.
  • We have used background class to style background which sets padding, text-align, bottom margin, width, height and font size of div element.
  • We have used .background::before psuedo element which sets the background-image, positions the background image using CSS position, top, left, bottom and right, sets the background-size.
  • CSS z-index property helps the background text to appear in front of the image.

Example

Here is the complete example code implementing above mentioned steps.

<html>
<head>
    <title>
        Placing background image using ::before 
        pseudo selectors in CSS
    </title>
    <style>
        .background {
            padding: 15px;
            margin-bottom: 15px;
            width: 500px;
            height: 500px;
            font-size: 20px;
            text-align: center;
        }
        .background::before {
            content: "";
            background-image: url("/https/www.tutorialspoint.com/html/images/logo.png");
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-repeat: no-repeat;
            background-position: center;
            background-size: 100%;
            z-index: -1;
        }
    </style>
</head>
<body>
    <h3>
        To place background image using 
        ::before pseudo selectors in CSS
    </h3>
    <div class="background"> 
        Welcome to the TutorialsPoint..
    </div>
</html>

Conclusion

In this article, we have used CSS background-image property along with ::before pseudo selector to place a background image in div element.

Updated on: 2024-08-06T17:32:16+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements