CSS background-color
The background-color property in CSS sets the background color of an HTML element. It is one of the most basic and widely used CSS properties to enhance the visual appearance of a web page.
What is background-color?
The background-color property allows you to apply a solid color to the background of elements.
You can use color names, HEX codes, RGB, RGBA, HSL, or HSLA to specify the color.
1. Using Named Colors
CSS provides predefined color names such as red, blue, green, etc.
Example 1: Named Color
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
background-color: lightblue;
}
</style>
</head>
<body>
<div>
This div has a lightblue background.
</div>
</body>
</html>
Output
• Uses a predefined CSS color name
• Easy for beginners
2. Using HEX Colors
HEX codes start with a # and are followed by 3 or 6 hexadecimal digits representing red, green,
and blue.
Example 2: HEX Color
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
background-color: #ff6347;
}
</style>
</head>
<body>
<div>
This div uses a HEX color (#ff6347).
</div>
</body>
</html>
Output
• HEX provides precise control over colors
• #ff6347 is a shade of tomato red
3. Using RGB and RGBA
RGB specifies colors with red, green, and blue values (0–255). RGBA adds an alpha value for transparency (0–1).
Example 3: RGB and RGBA
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
background-color: rgba(255, 165, 0, 0.5);
}
</style>
</head>
<body>
<div>
This div uses RGBA with transparency.
</div>
</body>
</html>
Output
• RGB values range from 0–255
• Alpha = 0 (transparent) to 1 (opaque)
4. Using HSL and HSLA
HSL defines colors with hue (0–360), saturation (%), and lightness (%). HSLA adds an alpha channel for transparency.
Example 4: HSL and HSLA
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
background-color: hsla(200, 70%, 50%, 0.6);
}
</style>
</head>
<body>
<div>
This div uses HSLA with transparency.
</div>
</body>
</html>
Output
• Hue defines color type
• Saturation = intensity, Lightness = brightness
• Alpha controls transparency
Important Notes
✔ RGBA and HSLA allow transparency
✔ Helps enhance readability and style