How not to do CSS

How not to do CSS

Common pitfalls that developers fall into when writing CSS, leading to bloated and hard-to-maintain codebases

Overusing !important

css
Copy code
.button {
  color: blue !important;
}

.button-important {
  color: red !important;
}

The !important rule in CSS is used to make a particular property and value the most important among conflicting rules. The !important declaration overrides any other styling rules, making it difficult to debug and maintain CSS. It leads to a specificity war where the only way to override a style is by using another !important, leading to a messy, hard-to-manage stylesheet.

Excessive Use of IDs for Styling


#header {
  background: #f1f1f1;
}

#footer {
  color: #333;
}

IDs are highly specific and should be used sparingly for styling purposes. Overuse of IDs in CSS makes it hard to reuse styles and can lead to specificity issues, where styles cannot be easily overridden by class selectors.

Not Using Shorthand Properties

.margin-example {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
}

CSS offers shorthand properties to make your stylesheets more concise and easier to read. Not using shorthand properties, as seen above, can lead to unnecessarily verbose code. This could be simplified to:

.margin-example {
  margin: 10px 20px;
}

Using Inline Styles Excessively

<div style="background-color: #000; color: #fff; padding: 20px;">Content here</div>

Inline styles mix content with presentation, making it hard to separate concerns and maintain styles. They also have a high specificity, overriding external stylesheets and leading to inconsistency and duplication.

Not Using Responsive Units

.container {
  width: 960px;
}

Using fixed units like pixels (px) for layout dimensions can make your site unresponsive. It's essential to use relative units like percentages (%) or viewport units (vw, vh) for layouts to ensure your site is accessible and looks good on all devices.

Over-nesting in Preprocessors

.nav {
  ul {
    li {
      a {
        color: blue;
      }
    }
  }
}

While CSS preprocessors like SASS can enhance productivity, over-nesting selectors leads to overly specific CSS rules, making it hard to override styles and leading to bloated CSS files.

Css can be simultaneously be the easiest and the hardest language to learn. Some good practices go a long way in maintainability .