Your website will be viewed on more than just a screen. Users might print a page, use a screen reader, or require higher contrast to see content clearly. CSS provides tools to cater to all these needs.
1. Print Stylesheets
When a user prints your page, you don't want to include the navigation, footer, or interactive elements. You can define a specific set of styles for printing using the @media print at-rule.
Code Snippet: Basic Print Styles
CSS
/* This is your main stylesheet (screen.css) */
body {
font-family: 'Helvetica', sans-serif;
color: #333;
}
.main-nav, .sidebar, .footer {
display: block; /* Visible on screen */
}
/* These styles ONLY apply when the page is printed */
@media print {
body {
font-family: 'Georgia', serif; /* Serif fonts are easier to read on paper */
color: #000;
}
/* Hide unnecessary elements */
.main-nav, .sidebar, .footer, .ads-container {
display: none;
}
/* Ensure links are identifiable even without color */
a::after {
content: ' (' attr(href) ')';
}
}
2. Accessibility (a11y)
Accessibility means designing your site so that people with disabilities can use it. CSS plays a vital role.
- Focus States: Never remove outlines on focused elements without providing a clear alternative. The :focus-visible pseudo-class helps by showing focus rings only for keyboard users.
- Reduced Motion: Some users experience dizziness or nausea from animations. The prefers-reduced-motion media query allows you to disable non-essential animations for them.
Code Snippet: Accessibility Enhancements
CSS
/* Provide a clear focus style for keyboard navigators */
:focus-visible {
outline: 3px solid #3498db;
outline-offset: 2px;
}
/* Respect user's motion preferences */
@media (prefers-reduced-motion: reduce) {
/* Disable all transitions and animations */
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
3. High Contrast Mode
Some users with visual impairments enable a high-contrast mode in their operating system to make text more readable. You can use the prefers-contrast media query to adjust your design accordingly.
Code Snippet: Supporting High Contrast
CSS
/* Style for users who prefer more contrast */
@media (prefers-contrast: more) {
/* Make borders more prominent */
.card, .btn {
border: 2px solid currentColor;
}
/* Ensure text has a very high contrast ratio */
h1, h2, p {
color: black !important;
background-color: white !important;
}
}