CSS Best Practices

Graphic showing anatomy of CSS rules

5 CSS Best Practices

CSS is a language that is used by nearly every developer at some point. While it's a language that we sometimes take for granted, it is powerful and has many nuances that can help (or hurt) our designs.

Here are 5 best CSS practices that will keep you writing solid CSS and avoiding some costly mistakes, courtesy of Envato and our textbook. Download a CSS3 Cheat Sheet here.

1. Make it Readable

The readability of your CSS is incredibly important, though most people overlook why it's important.

Great readability of your CSS makes it much easier to maintain in the future, as you'll be able to find elements quicker. Also, you'll never know who might need to look at your code later on.

2. Organize the Stylesheet with a Top-down Structure

It always makes sense to lay your stylesheet out in a way that allows you to quickly find parts of your code. A top-down format that tackles styles as they appear in the source code is recommended. So, an example stylesheet might be ordered like this:

  1. Generic classes (body, a, p, h1, etc.)
  2. #header
  3. #nav-menu
  4. #main-content

3. Create Your HTML First

Many designers create their CSS at the same time they create the HTML. It seems logical to create both at the same time, but actually you'll save even more time if you create the entire HTML mockup first. The reasoning behind this method is that you know all the elements of your site layout, but you don't know what CSS you'll need with your design. Creating the HTML layout first allows you to visualize the entire page as a whole, and allows you to think of your CSS in a more holistic, top-down manner.

4. Configure a Flexible Container

Flexbox is typically used to configure a specific area of a web page rather than the entire page layout. To configure an area on a web page that uses a flexbox layout, you need to indicate the flex container, which is the element that will contain the flexible area.

Use the CSS display property to configure a flex container. The value flex indicates a flexible block container. The flex-wrap property configures whether flex items are displayed on multiple lines. Configure the flow direction of the flex items with the flex-direction property.

5. Configure Flex Items

It's not always necessary to list all three values when configuring the flex property. The table below describes some common situations encountered when configuring a flex item.

Flex Item Examples
Flex Item Situation Shorthand Notation Equivalent
Fully Flexible Item: free space evenly distributed flex:auto; flex: 1 1 auto;
Fully Inflexible Item flex:none; flex: 0 0 auto;
Partially Flexible Item: shrinks to minimum size if needed flex: initial flex: 0 1 auto;
Proportional Flexible Item: the item takes up the specified proportion of free space in the container. For example: flex: 3  

Back to top