Skip to main content

Optimizing CSS

A website built on optimized CSS loads faster and runs more smoothly, and users get a better experience as a result.

The tips below show how:


1. Use Simple Selectors

Complex selectors cost more processing time, so prefer simple ones wherever you can.

Bad Example

Parsing is slowed by a long, deeply nested selector like this one.

styles.css
body #navlist ul li a.button:hover {
background-color: blue;
}

Better Example

Shorter and simpler, this selector is both faster and easier to maintain.

styles.css
.button:hover {
background-color: blue;
}

2. Avoid Universal Selector for Styling

Because the universal selector (*) targets every element on the page, it can slow down rendering. Reserve it for cases where it is strictly needed.

Example

styles.css
* {
margin: 0;
padding: 0;
font-size: 16px;
}

3. Avoid Inline Styles

Inline styles add weight to your HTML and make it harder to manage, so skip them unless they are necessary.

Bad Example

index.html
<div style="color: red; font-size: 18px;">Hello</div>
<p style="color: blue; font-size: 16px;">Test</p>

4. Avoid @import

Loading external CSS through @import delays the stylesheet, so it is best avoided.

A <link> tag in the head section is the better route, since the CSS then loads before the page is rendered.

Example

index.html
<link rel="stylesheet" href="style.css">

5. Use Shorthand Properties

Shorthand properties take up less space and parse faster, so reach for them whenever you can.

Example

styles.css
/* Long version */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;

/* Shorthand version */
margin: 10px 20px;

6. Cut Down Unnecessary Animations

Performance suffers when animations are numerous or complex, because they demand more processing power. Keep only the ones you need.


7. Use Properties that Do Not Cause Repaint of Animations

Which properties you animate also affects animation performance.

Steer clear of animating properties such as width, height, left and top, because each change triggers a layout recalculation.

Prefer ones that do not cause repaint, such as transform, opacity and filter, whenever you can.


8. Combine and Minify CSS

Smaller files come from stripping out spaces and comments, and one CSS file is better than several whenever possible.

CSS Minifier, PostCSS and online compressors are examples of tools that help.


9. Cache Your CSS

A long expiration time in your server settings lets the browser cache your CSS file, so users have to re-download it less often.


Summary

  • Short, simple selectors win
  • Layout-thrashing operations are best avoided
  • Animation techniques should be efficient
  • Stylesheets should be external, minified and cached