CSS Architectures: New Best Practices

This entry is part 2 of 5 in the series CSS Architectures

CSS Architectures

As you are well aware, the world of front-end development has evolved a lot over the past several years, as fresh minds have devised new approaches to solving age-old problems. Here are some of the latest best practices for front-end coding that will help your stylesheets and HTML considerably.

Reset with Normalize.css

CSS resets help establish a baseline from which all the styles are set. A reset effectively overrides the browsers’ default styles for certain elements (which can vary greatly). Despite the popularity of CSS resets over the past several years, many sites still don’t employ them, and these sites’ CSS scalability is suffering greatly for it.

Instead of using the extremely popular CSS Reset by Eric Meyer (because it is too far-reaching) or making up a DIY reset, many people recommend using normalize.css. Normalize.css “normalizes” the code to a common baseline rather than resetting the base styling for elements across all browsers. Referring to the normalize.css project on Github, these are its advantages over a CSS reset:

  • Preserves useful defaults, unlike many CSS resets
  • Normalizes styles for a wide range of HTML elements
  • Corrects bugs and common browser inconsistencies
  • Improves usability with subtle improvements
  • Explains what code does using detailed comments

Using normalize.css in lieu of a standard reset will get you on the right coding foot and save a lot of time in not having to reestablish baseline styles.

Get a Clear Fix on Clearing Floats

If you are still rockin’ the method shown here to clear floats in your documents, then we really need to talk:

<div class="clear"></div>
...
.clear { clear: both; } 

Other clearing methods are recommended over this one, which is one of the first float-clearing methods devised when CSS layouts with floats first started to be implemented roughly 10 years ago.

The Micro Clearfix, used in the HTML5 Boilerplate, employs the most up-to-date, tried-and-true, front-end coding best practices.The Micro Clearfix supports Firefox 3.5 and later versions, Safari 4 and later, Chrome, Opera 9 and later, and Internet Explorer 6 and later. Here’s an example:

/* For modern browsers */
.cf:before,
.cf:after {
  content:"";
  display:table;
}

.cf:after {
clear:both;
}


/* For IE 6/7 (triggers hasLayout) */
.cf {
  *zoom:1;
}

The clearfix .cf class should be added to all elements that contain floats. In such a case, the old-school empty divider element with clear applied (<div class=”clear”></div>) can be permanently retired from your repertoire.

What About Overflow: Hidden?

Another popular technique for clearing floats is to use overflow: hidden, although the Micro Clearfix is more highly recommended because there are sometimes issues with the overflow: hidden method in Internet Explorer 7 and earlier versions.

Although the use of overflow:hidden was almost everyone’s favorite float-clearing technique for a while, it raised problems such as these:

Louis Lazaris, coauthor of HTML5 and CSS3 for the Real World, suggests that using overflow:hidden causes problems in complex layouts and recommends avoiding it in favor of the Micro Clearfix.

If you are bound and determined to rock overflow:hidden, then use the following version of it, which makes allowances for hasLayout in Internet Explorer and block-level elements:

.container { 
  overflow: hidden;     /* Clearfix! */ 
  zoom: 1;              /* Triggers "hasLayout" in IE */ 
  display: block;       /* Element must be a block to wrap around contents. Unnecessary if only 
                        /* using on elements that are block-level by default. */ 
}

Dividers

Speaking of incorrectly wielding empty divs … you’ve got to stop rockin’ the empty cleared <div> with a border assigned to it as a page divider as well:

<div class="divider"></div>
...
div.divider {
border-top: 1px solid #ABAA9A;
clear: both;
} 

Yes, I know this code does a fine job as a clearing visual page divider, but it is not semantic. Nicole Sullivan, CSS ninja and creatrix of object-oriented CSS (OOCSS), suggests using the <hr> element to divide sections of the page and adding the necessary styling to it.

So instead of the preceding code, you would use this:

<hr class="divider">
...
.divider {
border-top: 1px solid #ABAA9A;
clear: both;
} 

Image Replacement

Front-end development has a long and illustrious history of CSS techniques for replacing text with images. In March 2012, Jeffrey Zeldman introduced a new kid on the block, deemed the Kellum Method. Instead of hiding the text off screen using the -9999px hack (and creating a huge invisible box in the process), his technique hides the text while leaving it accessible to screen readers.

.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

Performance is improved, notably on tablets and smaller screened devices.

Use an Icon Element

You might be using <span></span> as the way to put icons in your pages, like so:

<li class="favorite">
<span class="icon favorite"></span><span id="favorite-insert-point" class="favorite"></span>
</li>

If so, try this on for size: icons can be employed with an icon element, leveraging the <i> tag. This approach is becoming increasingly popular following its employment in Twitter Bootstrap.

<p><i class="icon icon-comment"></i>23 comments</p>
...
.icon { background-image: url( sprites.png ); }
.icon-comments { background-position: 0 -30px; }

The use of <i> is a bit more semantic than using a standard <span> tag, and makes it easier to identify where the icons are in your pages.

Get on the CSS3 Train

Often, sites use images for elements where it just isn’t necessary and become image-heavy. Using CSS3 helps tremendously with eliminating those images while getting the site prepped for moving to responsive design practices. For most sites, CSS3 is a boon for any instances of rounded corners (border-radius), drop shadows (box-shadow), text drop shadows (text-shadow), gradients and box-sizing.

However, there are two downsides to CSS3: first, many parts of the CSS3 specification are still in flux, so even modern browsers require vendor prefixes for most of the properties. Second, CSS3 is not supported by the popular older browsers, and thus requires fallbacks or helper scripts.

CSS3 Compatibility

Unfortunately, the older versions of Internet Explorer have the most compatibility issues with CSS3. Currently, CSS3 is only partially supported by Internet Explorer 9 (most notably, the CSS3 selectors; see HTML5 and CSS3 Support for an up-to-date list), and is completely unsupported by Internet Explorer 6 through 8. If you plan to use any CSS3 properties, I recommend having the proper fallbacks installed for the audience using Internet Explorer 9, 8, or earlier versions.

Luckily, there are scripts that help this. Support of CSS3 in Internet Explorer is aided by the following:

The downside of these scripts is that they increase page weight and load time, but the tradeoff is worth it.

Tools for CSS3

An overview of CSS3 and which properties are safe to use now could be the subject of a separate article. One of the most important steps with regard to CSS3 is to stay up to date with the changes to the specifications and the browsers’ adoption of them. Keeping track of all this can be a bit of a pain, so I suggest using the sites at http://css3please.com/ and http://html5please.com to keep up to date with the latest in the syntax changes and support. Many great CSS3 generators are available. For almost all of the properties, CSS3, Please! is a fantastic resource. For gradients, Ultimate CSS Gradient Generator is a great tool for generating gradient code with the proper syntax and fallbacks.

If you’re feeling particularly lazy and don’t want to have to remember how to write out all of the vendor prefixes, Prefixr will add them for you to your code. You can also use this great script by Lea Verou, which will add all the prefixes to your CSS after it is uploaded to the server.

Institute a Grid

If your site is currently without an established grid, you must “hie thee hence” and institute one. If your current code boasts a large number of instances of width, margin, and padding, with inconsistent dimensions between elements that are supposed to be the same size, then your site is long overdue for a grid.

You can construct your own using the dimensions of your elements, or you can employ a premade CSS grid framework (of which there are dozens, even responsive ones).

Use Box-Sizing

If you’re making your own grid, one incredibly useful CSS property to employ is box-sizing. Box-sizing can change how the browser calculates the size of an element’s box, and it is a god-send for dealing with dimensions, especially for layouts and grids.

Box-sizing calculates the dimension of an element’s box according to what was known as the “IE box model”—that is, the padding was considered in the size of the box. That means that when an element’s width and padding were declared together, the box would equal the amount of the width, and not the amount of the width plus the padding. Figure 1 illustrates this idea.

Comparison of the W3C Box-Model with the Internet Explorer Box-Model

Figure 1 Comparison of the W3C Box-Model with the Internet Explorer Box-Model

Using box-sizing: border-box (as opposed to box-sizing: content-box, which is the default based on the W3C box model) could be a real boon in making the calculations for layouts that much easier. The property box-sizing does require vendor prefixes.

Make the Grid and Images Fluid

The final aspect of planning to institute a grid (if you are thinking ahead to be future-friendly) is to make the switch from a fixed pixels grid to that of percentages (or ems). The best way to determine the percentages for sizes is to use Ethan Marcotte’s responsive Web design golden formula: target=content/context. Thankfully, there are calculators that can help determine the RWD numbers for the grid. I recommend RWD Calculator.

Also critical to being future-friendly is to have images that adapt and move with the size of their container. The main way to establish this is a simple line of code:

img {
max-width: 100%;
height: auto;
}

The images will now shrink or grow within the fluid container.

And Don’t Forget HTML5

Finally, HTML5 is definitely critical moving forward for all websites in general. It is no longer a question of whether a given site decides to implement it but a question of when. There are several aspects of HTML5 that I feel will be useful for anyone to employ at some point to lay the foundation for responsive design, but the easiest place to start is with the HTML5 doctype. The HTML5 doctype is a quick change that you can make to your page templates immediately as a precursor to moving to HTML5 tags and document restructuring.

<!DOCTYPE html>

Nothing else in your documents need to be changed because the doctype is backward compatible, but if any HTML5 tags are introduced, they will work.

Speaking of tags, another aspect of HTML5 to leverage is to employ some of the new tags, which help the page semantics while setting a good foundation for creating code modules. However, as with CSS3, backward browser compatibility is a serious consideration. To support the recognition of the new tags, scripts have to be used on the pages to enable older browsers to render the HTML5 elements correctly.

The most common script is HTML5 Shiv, which allows the HTML5 elements to be recognized by Internet Explorer 6 through 8. The only disadvantage is that there is yet another script to add to the page load. But really, there is no need to wait to use HTML5, so dive in!

Nice, Clean and Ready for Some Major Restructuring

That wasn’t so bad, was it? By cleaning up the code on the macro level by giving it the proper structure, and then zooming down to organize your code on the micro level, you can do a lot to improve heinous CSS. Further replacing outdated solutions with more efficient best practices helps considerably as well.

So now that we have the preliminary clean up out of the way, we’re ready to get down to some serious CSS restructuring. A site’s stylesheets can be taken to the next level of maintainability and efficiency by instituting some of the methodologies of the increasingly popular scalable CSS architectures.

Hang tight; you’ll get an overview of the top-four approaches in the next article in this series.

CSS Architectures

<< CSS Architectures: Principles of Code CleanupCSS Architectures: Scalable and Modular Approaches >>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://r.je Tom B

    Great post! It’s good to keep things up to date.

    My only concern is here is redefining a tag. Using for “icon” feels quite unnatural and semantically invalid. Using isn’t very helpful either, perhaps a better method is to use the tag.

    Where icon.png is a transparent png.

    • http://denisejacobs.com Denise Jacobs

      @Tom B – Don’t shoot the messenger! In the article I’m sharing new approaches to old problems. They are using this technique in Twitter Bootstrap (and those developers are far more hard-core than I am). If the technique doesn’t resonate with you, no need to employ it.

  • Richard

    Great series of articles so far, looking forward to more :) I’d like to hear what you have to say about writing good selectors into the HTML itself. Too many sites stick a class or ID on nearly every tag when it’s just not needed- you should be able to write really clean, lean HTML and keep selectors similarly lean. But… I’ve never read an article on best practice. Thanks again!

    • http://denisejacobs.com Denise Jacobs

      @Richard – Glad you liked the article! There should be a few more coming in the next several weeks, I think.

  • Adam

    I have a comment regarding your separator examples. Given that semantics primarily matter to the end users of assistive tech, and more API/browser/AT combinations report ARIA doc structure than the native semantics of the HR element, your first example of a separator element would in fact be more meaningful than the HR, as long as it has the separator role added to it. There is nothing wrong with an HR, but the ARIA method is better if you want a separator with semantic value.

    Secondly, using an empty italic element for an icon is not only no better than an empty span, but is a misuse of an element and a miscommunication of its native semantics. It is a myth that the italic element’s native semantics are never communicated. You have not added a presentation role, either, which should be used if you are going to use mark-up to show an icon.

    • http://juleswebb.com Jules Webb

      I have to agree with Adam on using the i element for icons. It’s not semantic and misscommunicates to to browsers and search engines. I think using a span element or a :before pseudo element is a better option.

    • http://denisejacobs.com Denise Jacobs

      @Adam – Thanks for the information on ARIA, that is really helpful!

      @Adam & @Jules Webb – As for the use of the <i> for the icon, it’s merely a suggestion based on what is being used in Twitter Bootstrap. As I said in the comment to @Tom B below, it’s completely a matter of personal preference as to whether you choose to use it or not.

      • Adam

        Using HTML wisely and appropriately is less a personal preference than a responsibility; and the likes of Twitter can hardly be held up as examples of good development.

  • http://ideyatech.com Nicole I. Rivers

    This is very informative. I personally like using Twitter Bootstrap as the framework, it has very good set of CSS components, that includes the tag you mentioned above and clearfix. It also have the .input-append and .input-prepend class that are very interesting to use.

    Hope to read an article about tips on targeting media types using CSS3 Media Query.

    • http://denisejacobs.com Denise Jacobs

      @Nicole – Glad you liked the article! In terms of CSS3 Media Queries, I am sure there is a wealth of them already on Sitepoint.com, so you should have plenty of reading to keep you busy there.

  • http://derekthomaswood.com sheriffderek

    img {
    display: block;
    width: 100%;
    height: auto;
    }

    adding this display block prevents the little margin that appears under image.

    What do you think about that? Is there any negative to doing this?

    • http://stubbornella.org/content/ Nicole Sullivan

      @sheriffderek – Just give it a vertical-align: middle. It also removes the little space (part of the line height) that appears under images, but it has no known drawbacks.

      • http://denisejacobs.com Denise Jacobs

        @Nicole Sullivan – Thanks for giving feedback on @sheriffderek’s question, I really appreciate it!

  • Jimmy

    “The use of <i> is a bit more semantic than using a standard tag”
    In what way? It is an abuse of an element for the wrong reason, so any added semantics are incorrect, and saving a grand total of six characters does not seem worthwhile.

    • http://denisejacobs.com Denise Jacobs

      @Jimmy – Please see my replies to @Tom B, @Jay Wotlers + @Sai Pc, and others. I am merely the messenger. Choose the method that is right for you.

  • Bart

    Wouldn’t it be nice if all browsers standardized on a user agent style sheet instead of needing a reset? Here’s an idea, adopt normalize.css as the browser standard. Saves an HTTP request and a bit of file size.

    • http://denisejacobs.com Denise Jacobs

      @Bart – Ahhh, a dream world. Given the rapid pace of change in the industry in the last several year, your suggestion doesn’t seem completely out of the realm of possibilities. Time will tell!

    • Adam

      Depending upon what Normalise contains, that may or may not be sensible. Some form of standardisation would be very useful to us, but CSS-aware browsers should still present the typical default user agent styles. People who disable our CSS for accessibility’s sake really appreciate those defaults.

  • Robert

    The clear fix. I do not see way to add a class to an element when you can just add clear:both to the css rule for the div that you want to have clear the above divs. Although for some reason with html5 this does not always work for some reason. In that case I go back to what you say is bad, but it works. So to sum up way fix it if it is not broke.

    • http://denisejacobs.com Denise Jacobs

      @Robert – Some of the reasons that this new Clearfix is a better option are outlined in great detail by the creator of the solution, Nicolas Gallagher here: http://nicolasgallagher.com/micro-clearfix-hack/. Whether it is good or bad, I can’t say. But Nicolas would be the person to take up any in depth questions about it you may have.

  • Bart

    Same goes for containing floats. Why not a CSS property of contain:true? Should have been implemented a long time ago. Why aren’t browser vendors or spec writers looking at these use cases as inspiration for what the development community actually needs? Same can be said of image replacement and other common workarounds.

    • http://denisejacobs.com Denise Jacobs

      @Bart – Good suggestion. Maybe you should suggest that to the W3C?

  • http://jaywolters.com Jay Wotlers

    I dont think calling <i> the “icon” element is correct. It clearly is for Italics or “alternate voice or mood” (W3C).
    http://www.w3.org/wiki/HTML/Elements/i

    Since it makes more sense to use <em> or <strong> in those cases <i> is simply not used much like <b>. It does not mean that the <i> can now be called the “icon element”.

    • Sai Pc

      I completely agree,i do not understand how using i makes it more semantic??? thats totally absurd..i is italics..and i dont think icons are italic in nature..:

    • http://denisejacobs.com Denise Jacobs

      @Jay Wotlers + @Sai Pc – What I mean by “semantic” is that at least from a visual standpoint, if you are using <i> as the tag for icons, then scanning for it is easier and it makes sense that “i” goes with “icon”, which you don’t get with “span”, since that could be used for so many other items on a page.

      As said to earlier commenters, I am merely the messenger – I did not devise this system. If it doesn’t resonate with you, then no need to consider it.

  • http://www.opensourcevarsity.com Ivan Bayross

    I reach this post via a newsletter I received from Sitepoint.

    Thank you for a great post. Its incredibly detailed. Lucidly written and so very well linked to associated content.

    I enjoyed reading through it. I have definitely added to my CSS skills from this material.

    Great job.

    • http://denisejacobs.com Denise Jacobs

      @Ivan Bayross – So glad you enjoyed the article and that you got some valued from it. Woot!

  • http://fergusdesign.come Christan Fergus

    Careful using the new image replacement technique with IE7. I’ve been using the new technique for a while and it works great, but tends to give IE7 fits (I know I know, who would have thought?). I still have to target it directly and do the old -9999px method.

  • Evan Smith

    The interpretation I have of the architecture you’re describing is one that is fast-to-market, small, and has a shorter lifespan (or requires more rewrites across HTML and CSS).

  • http://stackoverflow.com/users/1399491/alex-w Alex Watson

    Using the star hack for triggering hasLayout is not standards-compliant CSS. I would just recommend using zoom:1; without the asterisk.

  • http://iclearstudios.com Alex Zokaei

    Great read a lot of usefull CSS updates I wasn’t aware of some of the newer methods such as the Clear Fix and the Divers css methods, unfortunately. I will have to make sure that I am utilizing these new practices for CSS, thank you for sharing