Styling Headings with CSS
CSS provides full control over the visual presentation of headings, separate from their structural level. This allows you to meet specific design requirements without compromising the semantic hierarchy.
For example, you can style an h3 to appear visually identical to an h2 while preserving its correct structural role for assistive technologies.
<style>
h3 {font-size: 1.5em; }
h2, .h3alt { font-size: 2em; }
</style>
<h2>This h2 will look the same...</h2>
<h3 class="h3alt">...as this h3</h3>
<h3>But this h3 will be smaller</h3>
This h2 will look the same...
...as this h3
But this h3 will be smaller
Using CSS, it is possible to preserve whatever visual design that the site requires without having to compromise the structure.
Best Practices
Make Font Sizes Flexible
Use relative units like rem or em instead of fixed units like px. Relative units allow text to scale when users adjust their browser settings. This helps people with low vision who need larger text.
h1 { font-size: 2rem; }
h2 { font-size: 1.5rem;}Ensure Enough Color Contrast
Your heading text must stand out clearly from the background. WCAG requires a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text (18pt or larger). Use a contrast checker tool to test your colors.
h1 { color: #1a1a1a; background-color: #ffffff; }Avoid using color alone to show importance. Some users cannot see certain colors, so always pair color with other cues like size or weight.
Add Space Around Headings
Spacing makes headings easier to read and helps separate sections. Use margins to create clear breaks between headings and the text around them.
h2 { margin-top: 1.5rem; margin-bottom: 0.5rem; }Keep Styling Consistent
Style each heading level the same way across your entire site. Consistency helps all users predict what to expect, which makes your content easier to follow.
Summary
When styling headings with CSS, remember these key points:
- Use headings in the correct order based on meaning
- Choose relative units for flexible sizing
- Meet WCAG contrast requirements
- Add spacing for readability
- Stay consistent throughout your site
By following these guidelines, you create content that is clear, organized, and accessible to everyone.
