Writing CSS

Structuring your CSS code and how to order your rules.

Writing Your Own Style

The design pattern that I typically use borrows from OOCSS, BEM, and SMACSS patterns. How you decide to write your own CSS is entirely up to you. Different websites that I create may have slightly different design patterns based on the needs of the site.

Combining the media object with a BEM-like CSS class structure.

<article class="card">
  <header class="card_header">
    <h2 class="card_title">Title</h2>
    <div class="card_image">
      <img src="image.png" alt="" />
    </div>
  </header>
  <section class="card_body">
    <p>The lazy ex-developer quickly uses GIFs, HTML, CSS, and JS on the World Wide Web.</p>
  </section>
  <footer class="card_footer">
    <p>Footer content</p>
  </footer>
</article>

And the associated CSS would look like this:

.card {
  background-color: white;
  border-radius: 1rem;
  padding: 1rem;
}

.card_header {
  border-bottom: .25rem double navy;
}

.card_title {
  margin: 0;
}
A CSS Card Pattern

TEOS

Loosely based on principles found in atomic design and object oriented CSS, as well as structure found in design systems and pattern libraries, here’s a suggested order for writing CSS.

  1. Tokens: Your basic colors, spacing, fonts, and other values used throughout your website, as well as global pseudo selectors.
  2. Elements: This would be where you would add your normalization rules and then any rules for your default elements.
  3. Objects: collections of elements, usually with classes, to make some thing: whether you call it a widget, component, or something else.
  4. Sections: Headers, Footers, Navigation, etc. Sections aren’t quite objects and aren’t quite layouts.
  5. Layouts: A combination of sections that make up a page.

Guidelines

It’s your code, and unless I’m the lead developer on your team, I’m not going to police your CSS. Write it however you want. Here are some CSS guidelines that have worked for me.

  1. Don’t write a CSS Rule until you need it.
  2. Go with the flow. Use the cascade.
  3. Be as simple as possible, but no simpler.
  4. Be semantic: If you want to make an error message red, .error is a better class name than .red. Think in objects.
  5. Don’t use ID selectors if you can avoid it. IDs are best use in URLs and for targetting elements with JavaScript, not to target elements with CSS.
  6. Be direct: If you want to target an element, it’s better to use .header-link rather than .header .link or .header > .link — At the point that you’re nesting selectors to target something is a good point to use a class instead.
  7. Be mindful of your selector specificity.