Maintainable CSS – Part 1 - Don’t move the burden

Maintainable CSS – Part 1 - Don’t move the burden

By James Myers


  • 22 June 2014
  • CSS, HTML, Maintainable

It was agreed in the not so distant past that it was a good idea to separate the CSS style from the HTML mark-up.  Using inline style in would result in bloated, repeated code that was also harder to read and to maintain. 

If the same styles were to be used throughout the site then by creating external CSS files and using generic classes to style your HTML you could reduce the amount of code in your HTML pages.  This would provide many benefits such as faster loading HTML pages and code that was easier to read and maintain.

Now in theory keeping the HTML as small as possible and moving the CSS externally is a good idea.   Creating reusable generic classes that can be applied to elements means less duplication of code thus resulting in smaller files. 

One problem that can arise is when people focus too much on keeping the HTML file small and use more over specific CSS in an effort to avoid adding more classes to their HTML elements.  Here all you are simply doing is moving the burden from the HTML to the CSS files.

HTML

 

<div id="#container">

    <div class="content">

        <div>

            <p><a href="">some text here</a></p>

        </div>

    </div>

</div>

 

CSS

 

#container .content div p a {color:blue;}

 

You could have added an extra class to the <a> tag to reduce the amount of CSS used rather than move the burden elsewhere like so:

HTML

 

<div id="#container">

    <div class="content">

        <div>

            <p><a class="blueText">some text here</a></p>

        </div>

    </div>

</div>

 

CSS

 

.blueText{color:blue;}

 

You can also reuse the same class on any other HTML element where you would want the same style without having to write more specific CSS

 

View part 2 in the series Maintainable CSS - Part 2 - Smaller CSS files