Set the background color of an element with CSS

To set the background color of an element, use the background-color property in CSS. This property accepts color values in various formats including color names, hex codes, RGB, and HSL values.

Syntax

background-color: color-value;

Example

Here's how to set background colors using different methods:

<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: #ff6b6b; color: white; padding: 10px;">
      This text uses a hex color code.
    </p>
    
    <p style="background-color: rgb(76, 175, 80); color: white; padding: 10px;">
      This text uses RGB values.
    </p>
    
    <div style="background-color: lightgray; padding: 15px; margin: 10px 0;">
      This div has a light gray background.
    </div>
  </body>
</html>

Color Value Options

Format Example Description
Color Names red, blue, green Predefined CSS color names
Hex Codes #ff0000, #00ff00 Hexadecimal color values
RGB rgb(255, 0, 0) Red, Green, Blue values (0-255)
RGBA rgba(255, 0, 0, 0.5) RGB with alpha (transparency)

Using CSS Classes

For better organization, define background colors in CSS classes:

<html>
  <head>
    <style>
      .highlight {
        background-color: yellow;
        padding: 5px;
      }
      
      .error {
        background-color: #ffebee;
        border: 1px solid #f44336;
        padding: 10px;
      }
      
      .success {
        background-color: #e8f5e8;
        border: 1px solid #4caf50;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <p class="highlight">This text is highlighted.</p>
    <div class="error">Error message styling</div>
    <div class="success">Success message styling</div>
  </body>
</html>

Conclusion

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

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

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements