Global styles: CSS Best Practices, Part 6

Global styles in CSS needs to be used with care. Creating too many global classes, can have unwanted consequences, be hard to maintain and force you into using !important.


Personally, I’m not the biggest fan of global styles. It should be kept to the actual global tags such as headings (<h1>, <h2> etc.), input fields, paragraph, list tags etc.

Of course some global tags can be useful. F.e. creating a .lead for your paragraphs, which a personal favourite of mine.

Using global styles in CSS can have several downsides, such as:

Increased specificity conflicts

When styles are defined globally, they are applied to all elements that match the selector.

This can lead to specificity conflicts when you want to target a specific element, as it may already have been styled globally. This can make it difficult to override styles and can result in unexpected behaviour.

Unintended effects

It can unintentionally affect elements that you didn’t intend to style. For example, if you define a global font-size, it may affect the font-size of elements you didn’t intend to modify, such as form inputs or buttons.

Maintenance issues

Global styles can make it harder to maintain your codebase over time. As your project grows, it can become more difficult to track down where certain styles are coming from and to make changes without unintended consequences.

What’s the alternative?

An alternative approach is to use classes and IDs to target specific elements in your HTML markup. By using specific selectors, you can avoid specificity conflicts and unintended effects. This approach also makes your code more modular and easier to maintain.

I personally prefer to use the BEM naming convention which is a system for naming classes, and is widely known to reduces conflicts and improve readability.

Using BEM focuses a lot less on creating global classes. Instead you write CSS per component (or “block”), and allows you to “control the narrative”. That way I can my websites become more consistent. Overall, using classes and IDs to target specific elements can help you write more maintainable and predictable CSS code.

Global Styles

Global

Example of global styles

body {
    font-family: 'Roboto', sans-serif;
    font-size: 1rem;
    line-height: 1.6;
    font-weight: 300;
}

Typography

Example of global typography styles

h1, h2, h3, h4, h5, h6 {
    font-weight: 700;
    color: var(--black);
}

h1 {
    font-size: 3rem;
    margin-bottom: 2.5rem;
}

h2 {
    font-size: 2rem;
    margin-bottom: 1.5rem;
}

h3 {
    font-size: 1.5rem;
    margin-bottom: 0.5rem;
}

More CSS best practices