Good and Bad CSS Practices for Beginners

With CSS3, we can manage media queries, utilize better background images and even handle animations that can be loaded faster on your website – depending on the host you use. These features have made the life of every web designer and developer easier.

That being said, not all web designers and developers follow best practices. If you want to be a good web designer/developer, writing clean, manageable CSS is a healthy habit to make your code easier to maintain as your project development progresses.

Even if you’ve been building web pages for a quite a while, you may still have a few bad CSS writing habits that you’re better off forgetting. This post will also introduce you to some techniques that will help you get the most out of CSS and write beautiful, manageable stylesheets.

Let’s begin:

Bad CSS Practices

Using the Same Rule Repetitively

A lot of beginners use repetitive rules for each element. If you want to create a rule for multiple elements, use a class attribute instead.

For instance, instead of repeating color: blue rule for every tags and ID:

#intro1 {color: #3498db; font-size: 10px; font-weight: bold;}

header {color: #3498db; font-size: 20px; background-color: green;}

#banner {color: #3498db; font-size: 30px; background-image: url(images/static.jpg);}

Use a class instead:

.blue {color: #3498db;}

Using an ID Selector for Multiple Elements

When writing CSS, there should only be one ID in the HTML. Always use the class attribute for multiple elements.

For instance, instead of:

<p id="big">This is a great heading.</p>

<p id="big">This is absolutely a greater heading.</p>

You should use:

<p class="big">This is a great heading.</p>

<p class="big">This is absolutely a greater heading.</p>

Over Using the !important Rule

The !important rule was conscripted in the mid-to-late 90’s to help web designers and developers override the rules of their style sheet. The !important rule prevails over all the previous styles and says, “I’m more important, forget about all of that other CSS and use me!“. Using this out of laziness will give you a headache later on as your style sheet will be harder to maintain.

For instance:

header { 
    color: #e74c3c; 
}
header.intro {
    color: #3498db !important;
    font-size: 20px;
}
header#capture { 
    color: #2ecc71; 
    font-size: 20px;
}

In the above example, the header color is red. Except the header with the class intro and the one with the ID capture. The importance of the entire rule (both the color and font-size in this case) is accomplished by the specificity of the selector.

If you use !important, it is added at a property level, not a selector level. This means that the color property has a higher importance than the font-size. The color is more important than the color in the header#capture selector too.

Recommendation: You should only use the !important rule when overriding styles in a user style sheet, overriding 3rd party code and inline styles as well as utility classes.

Using the !important rule is often considered a bad practice due to the clutter it can bring with one of CSS’s core mechanisms which is specificity.

Using Inefficient CSS Selectors

When you are using selectors, the longer it is, the higher specificity it will comprise. This can break the CSS cascade and mess up the styles of your site.

This can be avoided by not using IDs within the selectors as they are directly specific.

For instance, we have these long selectors:

#header #intro h1.big a {... }

#header #intro h1.big a.normal {... }

We can compress it up to two or three levels deep:

.big a {... }

.big .normal {... }

Using Tons of Webfonts

It is understood that typography is a fundamental element of good web design, branding and readability.

However, regardless of the viewport size and resolution, web fonts are crucial to good web design, UX, and performance. Each font is an additional resource and not all web fonts render text well.

Depending on how you optimize the font and how they are loaded, it may affect the page size and the rendering time.

It is recommended to use one or two (probably a maximum of three) web fonts for your site and fall back to the browser defaults to keep your site optimized.

Using Inline Styles

Using Inline Styles is probably one of the worst CSS practices that many web designers and developers are still doing to this day. It transgresses the main goal of why we use CSS – which is to separate style from the HTML structure. This breaks the specificity of web pages.

It’s considered a good habit to keep your CSS and HTML separate. When you add inline styles, it makes it difficult revising the design of your site and makes your code harder to manage.

However, you can use inline CSS for HTML emails as many rules are not supported by email clients. This is an important thing if you are creating newsletter designs.

Overall, inline styles are at the lowest level of the cascade as they’ll override all other styles, so you need to be careful when using it.

CSS Good Practices

Now that we’re done talking about bad practices in writing CSS, let’s now take a look at some of the good ones.

Use a CSS Table of Contents

It is recommended to use a CSS table of contents when starting your style sheets. This will help you track down your code easily as you move along. Keep things organized and you will write styles more efficiently.

Consider this example below:

/* Project Meta */

/* reset  */

/* general */

/* typography */

/* grid */

/* header */

/* footer */

/* Page template A */

/* Page template B */

/* Media Queries */

Make Your CSS Readable

Writing clean sets of rules involves making the code readable. Having a readable CSS makes it much easier to maintain in the future, as you’ll be able to find each rule more quickly.

There are two ways you can make your CSS readable.

1. One line Form

.box {background: #3498db; border: 1px solid black;}

2. Standard Form

.box {
background: #2ecc71;
border: 1px solid black;
}

Separate jQuery Plugin Stylesheets

If you are using jQuery plugins, you need to put their styles into another style sheet and name it an easily remembered name such as JS-plugin.css. This will help you organize all of your CSS, in particular when you need to add or modify styles of your jQuery plugin.

Use a CSS Reset

A CSS Reset (or “Reset CSS”) is a compressed or minified set of CSS rules that resets all the styles of your HTML. Adding a reset reduces browser inconsistencies by providing general styles that can be modified and extended.

The MeyerWeb is the most popular and widely use CSS reset, although there is another option which is normalize.css by Nicolas Gallagher. It’s a modern HTML5 kind of CSS reset. You can use a CSS reset by either placing the source file link in your HTML file or copying the whole CSS reset into your style sheet.

Add CSS3 Animations Last

It is recommended to add CSS3 animations last in your style sheets to avoid any discrepancy when editing rules higher in the sheet. This will make the web browser load the important and basic CSS first before executing the animations.

Combine Elements

If elements within your style sheet share the same rules, you can simply combine all of them in one line or in a standard form instead of rewriting code over and over again.

For instance, your h1, h2, and h3 elements might all share the same font-family and color.

h1, h2, h3 {font-family: 'Lato', sans-serif; color: #dadada;}

Use Shorthand Properties

Shorthand properties allow you to set the rules of numerous CSS properties simultaneously. Using a shorthand property will shrink your CSS and increase readability.

For instance, instead of using margin-top, margin-right, margin-bottom, margin-left separately you can simply use just one line.

#div {

margin-top: 10px;

margin-right: 10px;

margin-bottom: 3px;

margint-left: 4px;

}
#div {

margin: 10px 10px 3px 4px; // top, right, bottom left 

}

Always Use Comments

One of the best practices for writing CSS is placing a comment on each group of elements. This will give you an ease of accessibility when you are looking for a specific groups.

/* GENERAL RULE */

html,

body {

font-family: 'Lato', sans-serif;

height: 100%;

background: #ecf0f1;

overflow: hidden;

}

h1 {

color: #3498db;

text-align: center;

font-size: 35px;

margin: 100px 0px;

font-weight: 700;

}

Use CSS Preprocessors

This is is a hot topic lately. A CSS preprocessor is a scripting language that extends CSS and then compiles it into regular CSS files.

There are three primary CSS preprocessors available today, Sass, LESS, and Stylus. Using a preprocessor can help speed up your development process as it minimize the repetitive tasks such as placing hex color values, closing your tags and so on that every web designers and developers often encounters.

Compress Your CSS

Another way to write efficient CSS is to shrink the file size by using tools like CSS compressor or Minify CSS to help the browser speed up the loading time. This will remove white spaces, line breaks as well as repetitive CSS styles.

Use Hex Color Often

There are several opinions and arguments on the web when it comes to choosing between Hex color and color name values. Different browsers may be unable to define what some color names mean. Hex color values are assured of matching across a palette of 16,777,216 colors while HTML and CSS are limited to 140 colors. There are not names for all 16 million 24-bit colors, so Hex is a good choice when it comes to choosing and deciding which color variation you should use.

You can check the CSS Color Module Level 3 here for more information.

Validate

Validating CSS with the W3C free CSS Validator will help you check your code and see if there are any errors. Things like aforgotten closed bracket or missed semi-colon will be easily found by this handy tool.

Try it out!

What’s Next?

After discussing the good and bad CSS practices, it’s now time for you to apply what you’ve learned here.

A sign of maintainable HTML, CSS, and JavaScript is when web designers and developers can easily and quickly modify parts of the code without affecting other, unrelated parts.

What are your thoughts? What good and bad CSS practice can drive you off the wall? Please leave a comment below.

Comments

  • Christopher Kennedy

    Great post, but given that ~ 77% of all browsers now do not use vendor prefixes for transitions, I worry that this information might encourage bad practices going forward?

  • Tinny

    There always are newly added properties that need prefixes, I suppose this was just an example

  • Using utility classes (e.g. .blue) is typically discouraged these days because it can really hamper modularity and future maintenance.

    Using explicitly declared, repeated rules can be repetitive for development, but lend a ton of support to maintainability in the future. This along with a BEM type naming system (modular, avoids specificity issues) really help make projects more sustainable over the long run IMO.

  • promise Tochi

    Using a class of .blue solves no issue and is still repetitive. You get to litter your html elements with several classes of .blue. if i apply “color: blue” to 4 elements in css without the class, that is “color: blue” in 4 places, if i decide to use .blue, i still have to write “class= “blue”” in 4 places in my html. Only that littering your html is worse and that is not what the “class” attribute is meant for.

  • hexx

    I wouldn’t recommend using this guide for junior developers at all.

  • Charis Anargyrou

    Shouldn’t you include SCSS, LESS or something similar as best practice as it makes your stylesheets more modular and easier to maintain?

  • Craig

    I thought prefixes were being dropped in favour of experimental flags

  • Mateusz Sobczak

    Unlike in JavaScript, compacting CSS code into reusable classes can bite back. I’ll let somebody wiser speak on my behalf:

    “DRY is often misinterpreted as the necessity to never repeat the exact same thing twice […]. This is impractical and usually counterproductive, and can lead to forced abstractions, over-thought and [over]-engineered code.“
    — Harry Roberts, CSS Wizardy

    I would rather recommend following this guide:
    http://maintainablecss.com/

  • promise Tochi

    Prefixes has been dropped.

  • Лев

    You encourage to use class “blue”? Seriously? And scope styles by pages instead of modules? What a dumb article..

  • Tinny

    When? Flex for example needs them

  • Some useful points for beginners, I’m not sure shorthand is always necessary, depends on the context.