Usage of background-color property in CSS

The background-color property is used to set the background color of an element. It accepts color values in various formats including color names, hexadecimal, RGB, and HSL values.

Syntax

background-color: color | transparent | inherit | initial;

Example: Using Color Names

You can use predefined color names to set the background color:

<html>
   <head>
      <title>Background Color Example</title>
   </head>
   <body>
      <p style="background-color: blue; color: white; padding: 10px;">
         This text has a blue background color.
      </p>
      <p style="background-color: red; color: white; padding: 10px;">
         This text has a red background color.
      </p>
   </body>
</html>

Using Hexadecimal Values

Hexadecimal color codes provide more precise color control:

<html>
   <head>
      <style>
         .purple-bg {
            background-color: #9932cc;
            color: white;
            padding: 15px;
         }
         .orange-bg {
            background-color: #ff6347;
            color: white;
            padding: 15px;
         }
      </style>
   </head>
   <body>
      <div class="purple-bg">Purple background using hex value</div>
      <div class="orange-bg">Orange background using hex value</div>
   </body>
</html>

Using RGB Values

RGB values offer another way to specify colors with red, green, and blue components:

<html>
   <head>
      <style>
         .rgb-example {
            background-color: rgb(144, 238, 144);
            padding: 20px;
            margin: 10px;
         }
         .rgba-example {
            background-color: rgba(255, 99, 71, 0.5);
            padding: 20px;
            margin: 10px;
         }
      </style>
   </head>
   <body>
      <div class="rgb-example">Light green using RGB</div>
      <div class="rgba-example">Semi-transparent tomato using RGBA</div>
   </body>
</html>

Common Color Values

Format Example Description
Color Name blue, red, green Predefined color names
Hexadecimal #ff0000, #00ff00 Six-digit hex codes
RGB rgb(255, 0, 0) Red, green, blue values
RGBA rgba(255, 0, 0, 0.5) RGB with alpha transparency

Key Points

  • The default value is transparent
  • Use rgba() for transparency effects
  • The property applies to all elements including text, divs, and backgrounds
  • Color values are case-insensitive

Conclusion

The background-color property is essential for styling elements in CSS. Use color names for simplicity, hex codes for precision, or RGB/RGBA values for transparency effects.

Updated on: 2026-03-15T23:18:59+05:30

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements