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;
}
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.
- Tokens: Your basic colors, spacing, fonts, and other values used throughout your website, as well as global pseudo selectors.
- Elements: This would be where you would add your normalization rules and then any rules for your default elements.
- Objects: collections of elements, usually with classes, to make some thing: whether you call it a widget, component, or something else.
- Sections: Headers, Footers, Navigation, etc. Sections aren’t quite objects and aren’t quite layouts.
- 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.
- Don’t write a CSS Rule until you need it.
- Go with the flow. Use the cascade.
- Be as simple as possible, but no simpler.
- Be semantic: If you want to make an error message red,
.error
is a better class name than.red
. Think in objects. - 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.
- 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. - Be mindful of your selector specificity.