How to avoid CSS Spaghettification

CSS is a very powerful language for styling HTML pages but can get very complex and very difficult to manage if you do not follow some sort of order. Years of experience in CSS has taught me this:

  • Use a Framework first, I recommend Bootstrap (which is mobile first and progressive enhancement)
  • After the Framework, Have only 1 custom CSS using this order:
    1. Rules without Media Queries (which are the fall back default rules for all devices and also the rules for small devices up) using this order:
      • a) Rules for html tags: body | h1 | h2 | ul | p | a | img
      • b) Rules for your page classes ordered as they are positioned in the page: .navigation | .contents | .footer
    2. Rules with Media Queries using only “@media (min-width)” starting with lower numbers and increasing: 768px | 992px | 1200px (if possible use only these 3 break points, Bootstrap 3 uses these ones)
    3. Rules for other components grouping rules by functionality, always /*comment*/ them at the top and encapsulate them by using a unique top class: .gallery | .gallery .item | .gallery .item .caption
If you do all of this you will avoid CSS spaghettification and you will have full control.

Custom CSS example

/* 1. Rules without Media Queries (default rules for ALL devices) */
/* 1a. Rules for html tags */
body { }
h1 { }
h2 { }
ul { }
p { }
a { }
img { }
/* 1b. Rules for your page classes (ordered as they are positioned in the page) */
/* NAVIGATION */
.navbar-default { }
.navbar-default .navbar-nav { }
.navbar-default .navbar-nav > li { }
/* CONTENTS */
#content article { }
#content header { }
#content section { }
/* FOOTER */
.site-footer { }
.site-footer a { }
/* 2. Rules with Media Queries (rules for bigger devices and they add up) */
/* These rules affect devices from 768px width to infinite width */
@media only screen and (min-width: 768px) {
.navbar-default { }
#content article { }
.site-footer { }
}
/* These rules affect devices from 992px width to infinite width */

@media only screen and (min-width: 922px) {
.navbar-default { }
#content article { }
.site-footer { }
}
/* These rules affect devices from 1200px width to infinite width */

@media only screen and (min-width: 1200px) {
.navbar-default { }
#content article { }
.site-footer { }
}
/* 3. Rules for other components (with unique top class) */
/* CAROUSEL */
#carousel { }
#carousel .item { }
#carousel .item img { }
/* GALLERY */
.gallery { }
.gallery .item { }
.gallery .item. .caption { }

Resources


Contact me about: How to avoid CSS Spaghettification, by:

  
  WhatsApp    Email