SmartCodingTips

Text & Background Colors in CSS

Colors are a vital part of web design. CSS allows you to change both text and background colors using various formats like names, HEX, RGB, or HSL.

1. Text Color

Use the color property to change the text color.


p {
    color: blue;
}

h1 {
    color: #1e40af;
}

a {
    color: rgb(255, 99, 71);
}
            

2. Background Color

Use the background-color property to set an element's background.


body {
    background-color: #f9fafb;
}

div.highlight {
    background-color: yellow;
}
            

3. Color Value Types

  • Color names: red, blue, green
  • HEX values: #ff0000, #1e90ff
  • RGB values: rgb(255, 0, 0)
  • RGBA: Adds transparency (alpha): rgba(0, 0, 0, 0.5)
  • HSL values: hsl(120, 100%, 50%)

4. Applying to Specific Elements

You can use classes and IDs to apply colors to specific elements:


#warning {
    background-color: orange;
    color: white;
}

.note {
    background-color: #e0f7fa;
    color: #006064;
}
            

5. Contrast & Accessibility

Make sure there's enough contrast between text and background. Use online tools like the WCAG Contrast Checker to ensure your site is accessible.

Conclusion

Using text and background colors strategically can enhance readability and design appeal. Practice using different formats to understand which fits your project best.