How to Create Colored Text in HTML & CSS: A Beginner’s Guide
1. Basic color with CSS
- Inline style:
html
This is blue text.
- Internal or external stylesheet (preferred):
html
/style.css */.highlight { color: #1e90ff; }htmlThis is blue text.
2. Color values you can use
- Named colors: red, blue, green
- Hex: #RRGGBB (e.g., #ff6347)
- Short hex: #RGB (e.g., #f63)
- RGB: rgb(255, 99, 71)
- RGBA (adds opacity): rgba(255, 99, 71, 0.8)
- HSL: hsl(9, 100%, 64%)
- HSLA (HSL with alpha): hsla(9, 100%, 64%, 0.8)
3. Applying color to parts of text
- Wrap the portion in a span:
html
Normal colored text.
- Use multiple classes for reusability:
css
.accent { color: #e91e63; font-weight: 600; }
4. Text gradients
- Use background-clip for gradient text:
css
.gradient-text { background: linear-gradient(90deg, #ff6a00, #ee0979); -webkit-background-clip: text; background-clip: text; color: transparent;}
5. Hover and interactive color changes
- Change color on hover or focus:
css
a { color: #0077cc; transition: color 0.2s; }a:hover, a:focus { color: #005fa3; }
6. Theming with CSS variables
- Define variables once and reuse:
css
:root { –primary: #1f7a8c; –accent: #f08a5d;}.primary { color: var(–primary); }.accent { color: var(–accent); }
7. Accessibility & contrast
- Ensure sufficient contrast between text and background (WCAG recommends at least 4.5:1 for normal text).
- Test with tools or browser extensions and avoid relying on color alone to convey meaning.
8. Responsive considerations
- Make sure color combinations work in dark mode — consider using media queries:
css
@media (prefers-color-scheme: dark) { body { background: #111; color: #eee; }}
9. Examples
- Simple example:
html
Colored text with a class
- Gradient example:
html
Gradient Headline
10. Quick tips
- Prefer external stylesheets for maintainability.
- Use semantic HTML and classes, not inline styles, for scalability.
- Check contrast and test on multiple devices/browsers.
If you want, I can generate a small starter HTML file combining these techniques.
Leave a Reply