CSS Best Practices

Elika J. Etemad (fantasai) W3C CSS Working Group

Specs I've Worked On Since 2004

Pet Peeves: Indentation

Indent your code.

Foundations: Learn CSS

Learn CSS.

Foundations: Separate Content and Style

Foundations: Linearized Logical Source Order

Foundations: Linearized Logical Source Order

Reorder visuals by reordering the source
not by using order or positioning
unless there's a clear accessibility justification for keeping them out of sync.

Foundations: Linguistic Variations

Set the language (<html lang="…">) correctly for better typography.

Testing: Test without CSS

Turn off CSS.

If the page makes no sense, fix your markup.

Adaptability: Media Queries

Set media query breakpoints in em or ch, not always in px.

Adaptability: Media Queries

Try resizing the window...

Adaptability: Liquid Layouts and Relativity

What is your sizing based on?

Absolute units (like cm or px) are usually the wrong answer.

WARNING: Requires Critical Thinking

Testing: Test Multiple Environments

Defensive Coding: !important means Never Override

Defensive Coding: Defensive Use of Shorthands

.lowSpecificity { background: linear-gradient(red, maroon); }
/* … more stuff … */
#highSpecificity { background-color: green; }

Use shorthands. Protect yourself against invading rules!

Defensive Coding: Defensive Use of Shorthands

background: url(…) top left, url(…) bottom right, url(…) center;
background-repeat: no-repeat

Defensive Coding: Don't Over-escalate

z-index: 9999999999999999999999999999999999999;

Understand your code, and don't overkill.

Defensive Coding: Drop Dead Code

Tried something and it didn't work? Delete it now.

Defensive Coding: Code to Standard

Keep the Web open to everyone!

Testing: Test in Multiple Browsers

Testing in Chrome ≠ Works for Everyone

CSS Best Practices: Summary

Logical Source Order
Keep DOM order readable: for accessibility, mobile optimization, device adaptability, and long-term maintainability.
Liquid Layouts and Relativity
Use smart relative sizing: to optimize layouts while minimizing media query code forks.
Media Queries
Adapt to screen size changes; get font size adaptation free by using ems.

CSS Best Practices: Summary

Shorthands
Use shorthands to create a “blank slate”. Use longhands for only for targetted tweaking.
Never use direction or unicode-bidi.
Use the HTML dir attribute, because it's content, not style (and you can then use :dir() selectors).
Prevent zombie code
Dead code may come alive as CSS changes. Delete it before it does, and ruins your layout.

CSS Best Practices: Summary

Test in Multiple Browsers
Your favorite browser is not always right.
Don't use proprietary features!
Keep the Web open to everyone! Don't rely on the latest -WebKit- invention.
Turn off CSS
A well-coded page will be understandable without it.