My face in close-up.

Richard Blechinger

Web developer, designer, caffeine addict

How I structure my HTML and CSS

A question that has probably bugged every person who has ever had to deal with making a website is: How do I get my HTML and CSS in order?

I don’t know about you, but for me this question has persisted over many years. There’s so many different ideas too! OOCSS, RSCSS SMACSS, BEM, ITCSS, … you get the point. The thing about all of them (besides having mostly unpronounceable acronyms) is that they don’t feel quite right to me.

Now, I’m not saying they’re bad, they just didn’t quite fit me. However I did like BEM a lot, so I based my approach mostly on that. For those who are not quite up to speed, here’s a very rough overview of BEM.

BEM 101

BEM stands for “Block-Element-Modifier”. What this means is that your page is built on a series of blocks or components. Each block consists of a series of elements that make up the block. It’s written like this:

.block__element {}

For example for a search field you could write the following:

.search {}
.search__field {}
.search__button {}

Which provides you with a general element to style, and then separate classes to style the text input and the submit button in which you could put a magnifying glass icon or some such.

Now, the missing piece of the puzzle is the modifiers. What are they for? They have your back every time you need a variation of an existing element. They are written like this:

.block--modifier {}
.block__element--modifier {}

To continue on with the slightly contrived search field example: Imagine you want to put your search bar not only prominently on a search page, but also into the sidebar of your page. You might want to have a smaller search button for that, so you can go:

.search__button--small {}

And to this you apply all styles that make the button smaller than the original one (perhaps less padding or something along those lines).

Those are the basics of BEM! If you want to learn more, you should go and read up on the official BEM page. That should cover everything you need.

Pre- and Post-processing of css

Like so many other people, I don’t write plain old regular CSS these days. I use a CSS preprocessor. There’s varying opinions on which one to use (LESS, SASS, Stylus, ..) but I have comfortably settled on SASS, or more specifically the SCSS syntax.

The advantages of having a CSS preprocessor have been covered all over the internet and reading up on that is left as an exercise to the reader. My SCSS is also usually combined with sass-module-importer so I can import files from node_modules easily.

Also I use a post-processing for my CSS. Autoprefixer, to be exact. What this tool does is to take your CSS and write out all the required browser prefixes for you. To me this is a godsend. For example the flexbox spec changed a lot over the years.

I use SCSS, Autoprefixer and Gulp to get my CSS in shape.

I am not particularly (read: at all) fond of writing four different syntaxes for the same thing. Thanks to Autoprefixer, I don’t have to! It automatically pulls in information about what prefixes have to be used for the browsers you support and adds them to your CSS.

My current setting is to add prefixes for browsers over 1% of global usage share, which is somewhere around Internet Explorer 10 and above.

To get my assets in shape, I typically use Gulp for glorious auto-compiling whenever a file is saved. (Also I can hear the Webpack people wailing in the distance, I know it exists, I’ve used it, I’m okay with it, please don’t hurt me).

I only use normalize.css as a base library and do not usually include Bootstrap or any other library. I’m proficient in using them, but I normally feel that they bring a lot of unnecessary baggage.

How I write my CSS

Onto the meat of the topic at hand. How do I write my actual CSS? I’ll show you a code sample and then we’ll talk it over.

.search {
  &__field {}
  &__submit {}

  &--small &__field {}
  &--small &__submit {}

  &:hover {}
}

Woah, woah, woah! Hold up. Hold the horses steady. What is that mysterious ampersand syntax? What’s with the nesting? I call hax!

That is a part of SCSS you see right there. The ampersand gets replaced with the parent class (in this case .search). This makes writing SCSS-based BEM very convenient since you can essentially namespace all of your styles under one parent.

Only use modifiers on the block itself

And one more thing where I tend to differ from regular BEM: I only use modifiers at the top most component. So I wouldn’t write .search__submit-small, but instead use .search.search--small .search__submit. It tends to work out better for me.

Nested components

A fact of life is that you sometimes will have to deal with nested components. BEM doesn’t really specify how to deal with those, though. Some people argue for nesting multiple levels. Others argue that if you nest more than once, you’re doing it wrong. I use a middle way. Let’s assume a hero component with a navigation.

We start writing our CSS like this:

.hero {
  &__navigation {}
}

Now, how do you proceed adding the styles for navigation items? Some people suggest proceeding as follows:

.hero {
  &__navigation {}
  &__navigation__item {}
}

This may be okay for a certain level of nesting, but at some point you might end up writing selectors like this:

.hero__navigation__item__dropdown--right {}

And that’s just horrendous. Instead I opt to go for the following approach:

.hero {
  &__navigation {}
}

.navigation {
  &__item {}
}

The corresponding HTML would be like this:

<div class="hero">
  <ul class="hero__navigation navigation">
    <li class="navigation__item">Navigation item</li>
  </ul>
</div>

As you can see here, I assign the .hero__navigation class, but I also start a new navigation block at the same time! This allows me to create styles that apply to all navigations while at the same time apply specific styling to the navigation inside the hero block. Plus, it’s nestable to infinity!

The CSS file structure

Ah yes, the ever so tricky balance on where to put your files so you can find them again. Here’s how I go about structuring my files:

scss/
  website-name.scss
  _variables.scss
  components/
    _content-section.scss
    _hero.scss
    ...

There’s a main scss/ folder that contains all files. Inside of that is a file that I usually name after the website. In the case of this site, it’s called blechi.scss

This is where I write all my styles that apply to elements! We’re talking links, paragraphs, basic image styles and such here.

The other function of this file is to do all the importing of the other files. To give you an excerpt of the contents:

@import "variables";
@import "syntax"; // Syntax highlighting

@import "components/contact";
@import "components/slide";
@import "components/listing";
@import "components/hero";
@import "components/navigation";
@import "components/content-section";

// more imports

body {
  font-size: 25px;
  line-height: 1.4;
  color: $color-secondary;
  font-family: Muli, sans-serif;
}

a {
  text-decoration: none;
  color: $color-primary;
  transition: color 0.33s ease-in-out;

  &:hover { color: lighten($color-primary, 10%); }
}

The _variables.scss file is where I keep, well, my variables. They are usually color definitions, a basic spacing unit and other handy things I use all the time.

Then we have the components/ folder, which contains all components that I create for a site. It’s not nested in any way, all components are just inside there and done.

Each component gets it’s separate file.

Building out the HTML

Building the HTML is really mostly a matter of copying the BEM structure. There are a few components that I usually bring to the table though. One of those is the content section.

A content section is a self-contained piece of content with a sub component nested into it. An example of it can be found on this very page. If you look at the homepage of blechi.at, each of the sections is a content section component.

Use a content section block to maintain a shallow page structure

You can easily tell by the separator in between. Another example of this pattern was used on my Tempura project! where you can see the content sections because they are differentiated by background color.

So what does a content section make? Glad you asked! A content section consists of the following:

To give you an example, here’s the portfolio section of the homepage:

<div class="content-section__wrapper">
  <h3 class="content-section__title">Portfolio</h3>
  <p>
    Of course you will want to see what projects I work on and have worked on,
    so here is a list of my recent projects and what you can expect when you
    hire me! Secret world domination plans are excluded here of course.
  </p>

  <div class="portfolio">
      <a href="...">
        <div class="portfolio__card">
          <img class="portfolio__image" src="..." alt="Marivol">
          <div class="portfolio__meta">
            <span class="portfolio__title">Marivol</span>
            <span class="portfolio__year">2017</span>
          </div>
        </div>
      </a>
  </div>

  <div class="portfolio-links">
    <a class="portfolio-links__more" href="...">Look at more projects</a>
    <a class="portfolio-links__cta" href="...">Hire me for a project</a>
  </div>
</div>

Some attributes shortened for brevity

From this you can see that the section has a block, the wrapper, a heading, some introductory text, the actual portfolio component and a call to action component.

In case you ask what the wrapper is for, there’s a simple answer: It allows me to (for example) give the section itself a background color that is width-independent from the actual content. You can see this at the main call to action.

The content section wrapper keeps your content independent from the surroundings

The background is full-width, while the content is limited to 960 pixels width.

You can also see that I didn’t necessarily nest components every time I go a level deeper. This is because I intended the portfolio to be one cohesive unit, instead of many independent component. Also I separated the portfolio links from the main component.

This .content-section block is my secret weapon. It’s extremely versatile and can be re-used many times over. Also it lends itself to a uni-directional action flow as I like to call it.

I then stack many of these sections onto each other, which results in a very shallow page structure. Here’s the top-level elements of the homepage:

<html>
  <head>...</head>

  <body class="home" cz-shortcut-listen="true">
    <div class="hero">...</div>
    <div class="navigation">...</div>

    <div id="wait-who" class="content-section">...</div>
    <div id="portfolio" class="content-section">...</div>
    <div id="my-writings" class="content-section content-section--no-separator">...</div>
    <div id="work-with-me" class="content-section content-section--featured">...</div>

    <footer class="footer">...</footer>
  </body>
</html>

Simple enough, isn’t it? And thanks to the id attributes you can immediately tell where you are on the page. I’m really in love with this concept and I build a lot of my HTML around it.

There you have an overview of how I structure my HTML and CSS. So far I’ve used it successfully on three different projects: This page, Tempura and an as of yet undisclosed client project.

TL;DR

It’s time for the wonderful TL;DR:

And that is it! I hope you enjoyed reading this post. There are many more to come, which will let you in on more design tips and other fun things!

If you like what I’m doing, please consider supporting me on Patreon! Thank you. <3