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:
- Hiding content and child elements with no scrollbars when the browser window is smaller than the container.
- Interference with margins, borders, outlines and absolutely positioned PNGs.
- Application of CSS3 properties, such as box-shadow, text-shadow and transforms.
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:
- IE9.js. There is a great explanation of which properties are affected by IE9.js and what problems are fixed as well.
- Selectivizr
- CSS3 Pie
- CSS Sandpaper
- Modernizr
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.
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.
Denise R. Jacobs is an author, speaker, web design consultant, and creativity evangelist. Based in Miami, Florida, she is the author of The CSS Detective Guide, and co-authored InterAct with Web Standards: A Holistic Approach to Web Design.