How to set the background color of an element based on its content using CSS

Arif Billah Babu

         

  CSS



Image not found!!

You can use CSS and the :empty pseudo-class to target elements with no content and set their background color. Here's an example:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Set Background Color Based on Content</title> <style> /* Set default background color */ .content-box { background-color: #e0e0e0; padding: 10px; margin: 10px; } /* Override background color when content is present */ .content-box:empty { background-color: #ffcccc; /* Set your desired background color */ } </style> </head> <body> <div class="content-box"> <!-- This box has content, so it will have the default background color --> <p>This is some content.</p> </div> <div class="content-box"> <!-- This box has no content, so it will have the overridden background color --> </div> </body> </html>

In this example, the .content-box class sets a default background color. The .content-box:empty selector then targets elements with the class that have no content and overrides the background color. You can adjust the colors and styles according to your preferences.