On this series we will go through some of the common bad CSS practices, and How and why we should avoid them,

This series addressed to different developers levels from new developers to experienced ones

Series Brief

When It comes to writing CSS, New developers (even Experienced ones) think that
using things like animations and transfroms and new CSS rules makes their CSS good,

but they overlook one important fact, that is the good CSS based on certain goals which should be achieved to make you CSS:

  • predictable
  • maintainable
  • reusable
  • customizable
  • scalable

and how following these bad practices in your CSS conflict with these goals.

Overly Complicated Selectors

One of the common bad practices that many of developers fall into Is writing complicated selectors like the examples below:

#navbar ul li ul li div { }
#card article h1:first-child { }
#main-sidebar > div > h3 + p { }

Why ?

The more complicated a selector the more coupled it is to the HTML,

Let’s assume that we have a button that deletes or adds elements on our HTML when gets clicked,
at this point, your selector will be broken and the result will not be predictable ,

and this is the 1st conflict with our good CSS goals.

another thing to mention, That this CSS is not Reusable in any way because it depends on the structure of HTML elements,
So you can’t us it on any different HTML structure,

and this is the 2nd conflict with our good CSS goals

How ?

We can use Meaningful and readable classes names that illuminate host element position and surrounded context,
So I will Depend on BEM writing Methodology to achieve that like below

.navbar__subnav {}
.card__title {}
.sidebar__text {}

As you see our selector becomes readable and expresses about its host element,

and it can be reusable regardless of HTML elements structure.

On the second part of the series we will talk about Changing Layouts based on Parent element,

CSS - The common bad practices series1 - CSS - Complicated Nested Selectors
CSS3#CSS3CSS#CSS