Things I wish I’d known about CSS

28th Jun, 2020

I learned how to build websites the old fashioned way: looking at website source code and trying to replicate the things I saw. I threw in the odd book for the stuff I couldn’t see (like PHP/MySQL), and I was on my way.

This was back in 1999, when we’d write things like <font size="4" color="#000000"> and DHTML was a thing.

When CSS came along my approach to learning didn’t differ. But I really wish I’d taken the time to learn CSS properly: there was so much fundamental stuff I missed.

Here are some things I didn’t know that I wish I’d learned earlier.

Block, inline and inline-block

Even though I knew about these properties, I didn’t fully understand them for a long time.

Here’s a breakdown:

In the example below, block elements have a blue border, inline elements have an orange background, and our inline-block element has a red border.

See the Pen (@websmyth) on CodePen.

Images are inline

Images being inline by default isn’t a problem, but it can cause confusion when trying to position them or add vertical margins.

If your CSS reset doesn’t include this already, I’d suggest adding the following rule:

img {
	display: block;
}

That will make their behaviour much more predictable. You might also want to add max-width: 100%; to stop them breaking out of their container, too.

How height and width are calculated

By default, the width/height of a box is calculated by adding together the dimensions of the:

This isn’t usually a problem for an element’s height: we’re usually not too bothered about how content reflows vertically. The problems usually occur when trying to calculate an element’s width, especially if there’s more than one element in a row.

If we had the following CSS:

.some-class {
	width: 50%;
    padding: 2em;
    border: 0.1rem;
}

The total calculated width for .some-class would be:

50% + 4em + 0.2rem

That’s because of a property called box-sizing which has a default value of content-box. This value means the width property applies to the content area: everything else is added on top of this.

We can change this for all elements with the following rule:

* {
	box-sizing: border-box;
}

Returning to our example, the element’s width would now apply to the border, so our element’s total width would be 50%.

What happens to the border and padding? Those properties/values still apply, but they don’t affect the total width of the element: they sit within the defined area.

Check out this Codepen to see this in action:

See the Pen (@websmyth) on CodePen.

We haven’t discussed margin here because margin is the space between elements. For that reason, it is never part of this calculation.

Padding & margin aren’t the same

If an element has no background or border, it can appear that padding and margin are the same. They are not!

That makes padding useful for elements that have a background. We often don’t want the content to be close to the edge of the element’s box and padding helps us achieve that.

Margins collapse

This has been the source of frustration for CSS newcomers for a long time. Rachel Andrew describes the behaviour as:

When margins collapse, they will combine so that the space between the two elements becomes the larger of the two margins. The smaller margin essentially ending up inside the larger one.

If we have two block elements with margin-bottom: 1em on one element and margin-top: 1.5em on the element directly below it, the total space between the two elements would be 1.5em.

We can see that here:

See the Pen (@websmyth) on CodePen.

When two margins meet, the larger margin absorbs the smaller margin. If the margins are the same value, they absorb each other.

As soon as we know this, margin calculations become easier. It might also change our approach to managing them, and that’s where something like the Lobotomised Owl selector can be useful.

Note: Margins don’t collapse when the parent element is set to display: grid or display: flex.

Browsers have a default stylesheet

CSS stands for Cascading Style Sheets. It’s no surprise therefore that the cascade is one of the fundamental concepts of CSS.

Though we might be aware of how our own stylesheets interact with each other, we have to remember that there’s always a default browser stylesheet. This is loaded before any custom stylesheets, making it easy to redeclare existing values.

The declared styles vary by browser, but they’re the reason that, by default:

And many other things.

Even if a website only has a single stylesheet, that stylesheet will always be merged with the browser’s default styles.

Use relative units everywhere

Using pixels (px) is tempting because they’re simple to understand: declare font-size: 24px and the text will be 24px. But that won’t provide a great user experience, particularly for users who resize content at the browser level or zoom into content.

I started using em (and later rem) for font sizing early. It took much longer to feel comfortable using em and rem for other things such as padding, margin, letter-spacing and border.

Understanding the difference between em and rem is critical to making relative units manageable. For instance, we might use em for @media queries and vertical margins, but rem for consistent border-width.

The benefits of going all-in on relative sizing are well-worth the small adjustment in thinking that requires.

::before and ::after need content

When using either the ::before or ::after pseudo-elements, they require the content property, even if it’s left blank:

.some-class::before {
	content: '';
}

If this isn’t included, the pseudo-element won’t display.

The ch unit

The ch (character) unit is useful, particularly to set an element’s width based roughly on the number of characters in a line of text.

Only roughly? Technically, the ch unit doesn’t count the number of characters in a line.

ch is based on the width of the 0 character. Eric Meyer wrote that:

1ch is usually wider than the average character width, usually by around 20-30%.

If you’re using this to control the measure of paragraphs or similar, this is a useful distinction to be aware of.

Normal flow

This was a term I’d heard a lot but didn’t fully understand for a long time. The “normal flow” means that elements appear on the page as they appear in source code.

For instance, if we wrote:

<h2>Heading</h2>
<p>Paragraph text.</p>

We would expect <h2>Heading</h2> to appear before/above <p>Paragraph text.</p>. That is the normal flow.

If an element is taken out of the normal flow, that means it won’t appear in this place. Floated and absolutely positioned elements are good examples of this.

Styling :focus states

I first learned about :hover, :focus and :active pseudo-selectors in the context of styling links. At the time, all of the examples I’d seen looked something like this:

a {
	color: black;
}
a:hover,
a:focus,
a:active {
	color: red;
}

However, it’s better if we style our :focus states differently.

:focus is the state when a user tabs to or through focusable elements on a page (like links). When a user presses [tab], they don’t know where the focus will land.

Additionally, if a user focuses on already-hovered item, they won’t know where the focus is.

For all of these reasons, it’s best to style :focus in a different way to :hover and :active:. For instance:

a:hover,
a:active {
  	/* styles */
}
a:focus {
    /* styles */
}

:nth-child()

Check out this Codepen:

See the Pen (@websmyth) on CodePen.

Notice how it’s the odd-numbered rows with a background? Given our selector (p:nth-child(even)), we might expect the even-numbered rows to be highlighted instead.

However, the :nth-child() selector counts all sibling elements. Specifying an element in the selector (e.g. p:nth-child()) does not cause the selector to start counting from the first of that element type.

Instead, specifying an element in the selector means that the rule will only be applied to that type of element. If we switch our example to be p:nth-child(odd), we will see that:

See the Pen (@websmyth) on CodePen.

Returning to our first example, let’s assume we want the even-numbered p elements to have a background. In that case, we’re better off using a different pseudo-selector altogether: p:nth-of-type(even)

See the Pen (@websmyth) on CodePen.

This is demonstrates a key difference between :nth-child() and :nth-of-type(). It’s subtle, but knowing this might help to avoid some confusion.

Wrapping up

It’s easy to get to grips with the basics of CSS, but understanding how and why things work is critical to writing better CSS.

Taking the time to learn these things not only helped me to write CSS more quickly, but it has also helped to make my code more efficient and resilient.