
Good CSS is easy to read, change, and test. These practices cover how to structure a stylesheet, write selectors, and check the result across browsers.
1. Organize styles from general to specific
Start with shared settings and base element styles, then group layout and component rules. Keep each component’s states and responsive rules where readers can find them. Choose a consistent approach across files.
2. Choose predictable selectors
Prefer a class such as .product-card for a reusable component. Reserve IDs for unique references such as fragment links. A class selector usually keeps specificity easier to manage.
3. Use a consistent convention for multiword names
Choose a convention such as product-card and apply it consistently. See CSS class naming examples.
4. Make declarations readable
Use indentation, one declaration per line, and short comments that explain decisions. Apply the same formatting across the stylesheet.
5. Group selectors when they share a rule
h1, h2, h3 {
line-height: 1.2;
}A comma lists alternatives. Group selectors when the style is intentionally shared, so future edits to one component do not accidentally change another.
6. Keep descendant selectors short
.article a can style links inside an article. Long chains tie the styles to the markup structure and can increase specificity. Compare descendant and child selectors in the CSS selector guide.
7. Use shorthands where clear
margin: 1rem 2rem sets both vertical and horizontal margins. Shorthands can reset omitted subproperties. Use a longhand when changing one part should leave the others alone.
8. Choose descriptive names
A name such as .page-header tells the reader where the class belongs. Avoid isolated abbreviations unless their meaning is established in the project.
9. Name components by purpose
.primary-button can stay meaningful when the design changes. A name such as .big-red-button can be misleading once the appearance changes.
10. Test on different browsers
Check layout at small and large widths, then try keyboard navigation and zoom. Use real browsers and devices when possible. A service such as Browserling can help with browsers you do not have locally.
11. Validate the stylesheet
Run the W3C CSS Validation Service to catch malformed declarations and other issues. Confirm that the reported CSS profile supports the syntax you intend to use.
12. Add vendor prefixes only when needed
Check the browser versions you support. If your build uses Autoprefixer, configure it for those targets rather than maintaining prefixes by hand. Keep the standard declaration where appropriate.
13. Avoid using !important as a default
Inspect which declaration wins before trying to override it. Scope, rule order, specificity, and cascade layers can usually express the intended priority directly.
14. Check asset paths
Relative url() references in an external stylesheet resolve from that stylesheet. See file paths in HTML and CSS for worked examples.