15 CSS Habits to Develop for Frustration-Free Coding
By Jeremy Davis
It’s been said that the key to a civilization's success is mastery of the food system. Unless a group of people can effectively control the basic needs for survival, they will never achieve greatness. Likewise, before CSS skills can be expanded to an advanced level, the basics must become instinct to any CSS coder. Develop these habits and you lay a solid foundation to apply advanced CSS techniques.
1. Use a Reset Stylesheet
This habit (along with a few others) is one frequently mentioned as a CSS best practice. The goal of a reset stylesheet is to reduce inconsistencies among browsers by explicitly setting styles to most of the HTML elements. This ensures that things like font sizes and line heights all render the same on different browsers. Also, the reset clears the default paddings/margins that some browsers have.
Not only does having a reset stylesheet account for browser inconsistencies, it's good to use them to give each site a known foundation when coding. Keeping the foundation the same for all sites will speed along the development.
The reset from Eric Meyer and the Yahoo reset are the most comment resets used. Futher customizing one of those resets might be needed to accomodate for specific website needs.
2. Use CSS Shorthand
Using shorthand CSS declarations will lead to quicker coding and debugging. It might also save some errors from mistyping multiple declarations.
When a rule has multiple similiar declarations for a single selector, such as
border-top: 5px; border-right: 10px; border-bottom: 15px; border-left: 20px;
they can be combined into one line, such as
border: 5px 10px 15px 20px;
The trick to remember which position controls which direction is TRouBLe: Top, Right, Bottom, Left.
The main declarations that use shorthand for are border
, margin
, padding
and background
.
Bonus: Hex Shortcut
Six hexidecimal digits used for CSS colors can be condensed down to three if they are grouped in identical pairs.
For example, #FFFFFF
can be written #FFF
, or #990055
can be written #905
, but #F091A4
cannot be shortened since the pairs aren’t identical.
3. Document Your CSS … As You Go
Going back and commenting code is one of those quixotic things that most fool themselves into thinking they will do. Get in the habit of making good commenting practices while writing styles.
To add a comment in CSS it’s as simple as putting /* Your Comment Here */
Things to comment
Stylesheet Header
This comment briefly states what the stylesheet is for, who wrote it and when. A table of contents might also be needed for larger stylesheets.
Code sections
Put a comment header above large portions of code for things like global styles, headers, sidebars, main content and footer to help delineate them.
For example,
/****************************************/ /* Sidebar */ /****************************************/
Problem declarations
Put comments next to declarations that have know issues in certain browsers, such as
input[type=textbox] /* IE6 Problem */
Dependent declarations
Put comments next to things that are dependant on other areas. So if there is a fixed height on a declaration that might need to be adjusted if the content changes, put a small comment next to it, stating what conditions must happen before it will need to adjust.
4. Add a Color Legend
When working on smaller CSS files, keeping track of color hex values isn't too hard. But as stylesheets start getting 2000+ lines it becomes significantly harder to keep track of which value is for which color. Adding a color legend helps ensure that the wrong colors don't get used.
The best place for the legend is up in the stylesheet header, underneath all of the other documention.
For example,
/* /* light blue: #4595be /* dark blue: #367595 /* special link red: #9F1212 ********************************/
5. Remember Where Absolutely Positioned Elements are Relative To
Positioning elements absolutely is something that tends to frighten some CSS beginners, but there is one principle to remember with this declaration that solves most of the trouble.
When a selector has a postition: absolute
declaration the webpage is treated like a xy grid. By default, the 0,0 position of the grid is at the very top and left position on the webpage. So by moving the absolutely positioned element to the left 10 pixels and from the top 20 pixels, it’s starting from the top left of the webpage, regardless of where the element sits in the HTML.
That is not usually the desired functionality. What usually is desired is to have the element positioned relative to the selector's parent or another containing element. To do that simply add position: relative
to the desired relative container element. Doing that remaps the 0,0 position on the xy grid from the top of the webpage to the top left of the containing element.
The example below demonstrates how the red box gets positioned differenlty depending on whether the blue container has position: relative
or not.
Remembering position: relative
should ease most frustrations caused by basic absolute positioning.
6. Avoid Using CSS Hacks
Unfortunately for web designers, there are bugs in some browsers, mainly IE6 and IE7, that cause some styles not to display as they are supposed to in accordance with CSS specifications. In order to combate these inconsistencies, some people write erroneous declarations, hacks, that take advantage of these browser flaws in order to do things, such as hide styles from particular browsers
There are many fancifully named hacks for all the equally fancifully named CSS bugs, but using them can cause problems. Not only do hacks clutter the stylesheet with oddball declarations, it also keeps the stylesheet from validating.
Also, hacks tend to introduce more problems overtime as new browsers are released.
Instead, use conditional stylesheets to target specific browsers.
7. Use Margins When Styling Layouts
Although this habit isn’t one often mentioned, it's one that helps maintain a consistent layout among different browsers without having to add more declarations to get them all in sync.
The main idea is that instead of adding padding to a container element, add margin to the container’s children to get the same result.
So, instead of
#main-content { padding-left: 10px }
add
#main-content { } #main-content #left-column { margin-left: 10px }
Although there is nothing particularly wrong with using padding, in my years of building websites I have had consistenly fewer cross-browser problems when I stick with styling layouts with margin.
8. Contain Floats
When floating an element, add overflow: hidden
to its containing element.
A common example is,
ul { overflow: hidden; } ul li { float: left; }
If the container didn't have overflow:hidden
issues arise when setting margins or borders to it. This also clears the float so that elements below it can flow properly in the HTML structure.
Some suggest doing the clear in HTML by adding
<div style="clear:both"></div>
below the floated element, but doing that defeats the purpose of separating a webpage's style and structure.
It's also more time consuming than adding overflow: hidden
.
9. Add display: inline To Floated Elements
This habit is one that fixes a IE6 problem called the double-margin bug without having to use a CSS hack. On floated elements, IE6 doubles the margin of the element. So a margin of 10px becomes 20px.
It's easy to imagine the havoc an error like this can cause to a layout. Some of the floated items either become hidden or they push everything below it down.
Even though IE6 is on its way out and a majority of designers aren't taking the time to get sites looking perfect in IE6, this is a quick habit to learn to make a site better viewed for those poor people still on IE6.
Just get in the habit of adding
display: inline /* IE6 Problem */
every time something is floated.
10. Get Comfortable with Sprites
Sprites mask the viewable space of a larger image, then when an event occurs, typically a :hover
event, the viewable space of the image changes to show another portion of the image.
Not only are sprites more efficient by requiring fewer HTTP calls for images, but they add more polish to website designs. Most often sprites are used to create stylish navigation menus.
Using sprites in a design might take a bit of trial and error to get the hang of it, but it's such a valuable skill to have that it's worth the effort required to get the concept down
Further Reading
11. Have a Consistent File Structure
Take the time to create and organize all of the typical files used for a typcial website development project. Create one master template file structure and copy/paste it every time a website needs to be built.
My organization is as follows:
The 'Website Name' folder gets renamed to the website name that I'm about to begin work on. That folder contains all of my HTML files for the site, along with the 'assets' and 'styles' folders.
The 'assets' folder typically holds larger document files like PDFs that might need to be downloaded from the site. I also keep editible versions of images I'm using, such as PSDs or Fireworks PNGs, in case I need to modify something.
The 'styles' folder is broken into the three subfolders: css, images, javascript.
- css - holds all the css files, such as reset.css, layout.css and main.css
- images - holds all the images for the site
- javascript - holds javascript libraries, plugins and main.js
I use this file structure for most of my webpages and because I’m consistent I know exactly what paths to use when needing to do things, such as put a background image in my CSS.
Some might disagree with my structure, such as having javascript under 'styles', but the main point is find a file organization that works for you and get in the habit of consistently using it to make coding faster and more accurate.
12. Indent Your Styles
Adding indentation to a stylesheet can keep complicated stylesheets looking clean and make finding areas of code easier. Add indents to show a parent/child hierarchy.
13. Use Pixels for Font Sizes, Not Ems
This habit is usually a hot button topic with most people having a strong opinion for either fixed font sizes or relative ones.
In hopes to curtail a probably backlack, let me plainly state, "Using a fixed font size, like pixels, leads to fewer CSS frustrations than using a relative font size, such as ems or %."
In his article Coding Like It's 1999, Cameron Moll petitions for pixels and says,
The burden of calculating relative units throughout a CSS document is replaced by the convenience of absolute units
Relative font sizes were a good idea a few years ago so that people with different browser font sizes could have a site's content adjust to their browser’s font size. But now most browsers can zoom and adjust more intelligently so a relative measurement isn’t neeed for that purpose anymore.
Relative measurement becomes a problem because the font sizes inherit the parent's measurement as it cascades down.
For example, body { font-size: 62.5% }
makes a font-size: 1em
declaration equal to 10px.
If #blog-content
needs to be 14px, the rule is
#blog-content { font-size: 1.4em; }
Now the if the H3 tag inside of #blog-content
needs to be 20 pixels, one might assume
#blog-content { font-size: 1.4em; } #blog-content h3 { font-size: 2.0em }
would be right, but that's where the relativity problem occurs. Because that 2.0em is now relative to the 1.4em specified on #blog-content
, so it is actually font size of 28px.
Keeping up with relative font sizing can get confusing. Stick to using a fixed unit of measure for font sizes to prevent undue troubles.
14. Limit Pseudo Classes to Anchor Tags
Most modern browsers don't struggle with this problem, but it is an important one to remember if a website still needs to be viewable on older browsers, such as IE6.
The problem is that older browsers only recognize pseduo classes, like :hover
, on the anchor tag element, a
.
So something like
#header ul li:hover { background-color: #900 }
won't work in IE6.
This issue could cause real functionality problems, if things like dropdown menus are to appear based on the li:hover event. People viewing the site on IE6 would never see the dropdown and thus, might have a hard time navigating the site.
A solution is to use jQuery for those types of effects.
15. Avoid Selector Issues
Be sure selectors have enough weight to prevent unwanted cascades.
The way the browser determines what style is to be applied to an element with multiple declarations is determined by its specificity
The more specified a CSS selector is the more weight that rule carries. The rule with the heaviest weight is the one that gets applied to the element
If some rules are being applied as desired, check to see if the problem is with its specificity. It might be as simple of a solution as adding an #id-name
to the beginning of the selector.
Use element selectors when possible.
Instead of
main-content .main-header
use
#main-content h1
Be careful when grouping selectors.
Grouping selectors can be a time-saving method when dealing with non-relative declarations, like
.main-content div, .main-content p { color: #000; }
But it can cause trouble when using a relative declaration, such as
.main-content div, .main-content p { line-height: 1.3em; }
Because now all of the text within the div gets a 1.3em line-height applied to it, but now any p elements within a div get an additional 1.3em added to them.
Also, sometimes grouping multiple selectors can add more weight to them than is desired, which in turns causes other desired styles not to take place.
* Write Better HTML
Bonus Tip! A great way to become a better CSS coder is to improve your HTML coding.
Avoid div-itis by wrapping divs around everything. Learn to style the elements with element selectors, such as h1
, ul
and p
.
Use a proper DOCTYPE to avoid sending browsers into quirks mode.
Try to code as much HTML as possible before adding any styles. Doing this brings more thought to the overall structure of the webpage and causes syntax problems to be spotted and fixed instead of covering them up with styles.
Further Resources
Here are some articles that further explain some of the basics CSS principles mentioned here.- 7 Principles of Clean and Optimized CSS Code
- The Mystery of CSS Sprites: Techniques, Tools and Tutorials
- Mastering CSS Coding: Getting Started
- Powerful CSS Techniques for Effective Coding
- 53 CSS Techniques You Couldn't Live Without
About the author
Jeremy Davis is a recent college graduate working as a designer and front-end developer for a public school system. He (in)frequently blogs about web design, web development and technology on his personal blog. He is also *currently accepting more Twitter followers.
*offer ends soon, act fast.
From #6:
“Not only do hacks clutter the stylesheet with oddball declarations, it also keeps the stylesheet from validating”
Why is it important that your stylesheet validates?
It’s more of an added bonus. Some people do go crazy if the stylesheets don’t validate.
Because it helps prevent browser issues, bugs and sticks to a standard. Why follow the instructions when replacing the engine on your car? Why not just guess?
Although, I don’t mind a stylesheet not validating if it’s using progressive enhancements such as CSS3, since browsers that don’t support them will ignore them.
@Amber What makes a CSS hack that isn’t recognized by a browser any different from CSS3 that isn’t recognized by the browser?
can you link to specific examples where CSS hacks cause browser issue and bugs?
thx
It was pretty much a given, point 13 will create discussion…
My personal approach is creating a “base” font size in pixels, and then making all other measures relative in ems. That way I can update the font size for the whole document.
I like to see text as a dynamic block in the layout, so I think is for the best to left text as fluid as possible.
#8:
If you use overflow: auto instead of overflow: hidden, your element will grow in height as necessary AND you can use margins/padding. Just don’t set a height or you’ll get scrollbars.
For containing floated children, I don’t like using overflow at all. It works in most situations, but not all. The most consistent fix to containing floated children is this: http://net.tutsplus.com/tutorials/html-css-techniques/css-fudamentals-containing-children/
It’s more CSS yes, but I haven’t found a situation that it doesn’t work in, and it’s cross-browser, including IE6+.
I’ve used overflow:hidden quite a bit the main problem I have with it is that that to trigger the hasLayout in Opera or IE you’ll need to specify a width or height. For newer versions it works with width:auto but for IE6 you’ll need a px or % width which can be a pain (but using a separate conditional IE6 stylesheet will negate the problem).
The other issue with overflow:hidden is that you may sometimes want certain elements to actually overflow. E.g. hover effects, custom tool-tips etc. in which case you’ll need use an alternative solution.
The “new” .clearfix:after works in most cases as a replacement for but if you have multiple floated elements on the same page it can sometime “clear too much” and expand down past a parallel floated element.
I’m using both the “overflow” and “clearfix” solution. I’ve read a nice post at SmashingMagazine that the overflow works, but not in all situations. The clearfix is better, and works in almost browsers, even IE.
I stopped using the overflow in most cases as I use a lot of popup windows and hidden layers. When combining these with with the overflow set to hidden, the results are not good.
I agree with nearly all of these, the exceptions being number 7 and number 13.
I completely disagree that margins are more appropriate for layout than padding. Padding is, simply, applied more consistently than margins. Margins have 2 major layout issues: the double margin issue and inconsistent collapsing margins.
For the first, you applied another “rule” just to fix (number 9). When you float a block level element and apply a margin, IE6 will double it, like you stated. But this can be avoided just by using padding instead. I would think CSS best practices should not be IE6 specific, considering the browser will be dead in less than 2 years, while this article will live on forever (as long as this site exists) for new developers to find years after the browser is dead. So, consider that this problem can be avoided entirely by using padding, I would go that route.
The second issue is with how margins, specifically top and bottom margins, collapse cross-browser. You can read about those topics here: http://reference.sitepoint.com/css/collapsingmargins and here: http://www.complexspiral.com/publications/uncollapsing-margins/ or just look at this example: http://jsbin.com/uziso3/edit in FF/Chrome/Safari as compared to any version of IE.
And I have to say, I feel number 13 is a bit absurd. Even the quote, the “convenience”? Whose convenience? Certainly not the end user’s. If you’re coding something a certain way because it makes your job easier and not because it provides the best, most consistent user experience, you’re not doing your job.
Now I’m not saying “use em’s all the time”, whether you use em’s, percentages, or pixels should depend on the project. If your target audience is 18 – 21 year old people, who typically have excellent vision, go ahead and use a set font size. But if your audience includes a large range of people, some of which may have bad vision and need larger fonts, then using a set pixel size would be bad.
Ultimately, setting pixel size takes away control from the user to size the font they need it to be to make the site legible to them. This provides a bad experience of the site. I can’t see any argument of developer convenience overriding the user being able to use the site.
Regarding point 13, I think you need to read the post again. The author made it plain that the reason he recommends using pixels is that all modern browsers allow the user to zoom entire pages, thus making the use of ems or other non-pixel units redundant.
So, your claim that “setting pixel size takes away control from the user to size the font they need it to be to make the site legible to them” is false.
I believe that the newest browser this limitation still applies to is IE6, which no-one should be coding for any more.
I agree with RussellUresti on #13
The author might have made it clear that modern browsers zoom, but the author is also misguided.
You *can* increase the text size in modern browsers (IE7 view -> text-size -> largest) and users with visual impairments will do that, rather than zoom. Zoom can create a horizontal scrollbar, which makes it more difficult to navigate a page, when all you want is larger text to read because you can’t see it well.
Fabulous article in other respects though!
I tend to use ems, but I’m mixed. Like Russell said, whichever one to go with ultimately depends on the project. I usually try to set my font sizes at as high in the cascade as I can to avoid running into problems further down, but I realize that’s not always possible, especially on larger projects.
Regarding IE6 – ZigPress, your claim that “no-one should be coding” for it anymore is unrealistic. 99% of the people in my company have no choice but to use IE6 as long as they’re in our offices. And a large portion of the visitors to our website are using IE6 because they’re also in corporate environments stuck using IE6. If I ignored it that would alienate a huge number of our visitors, my bosses constantly be asking why our website looks screwed up. Yes it sucks, and I can’t wait for it to go away, but I can’t ignore it. I don’t bend over backwards to cater to it, but I still have to code for it.
I concur with the above, but for a different reason. If you specify pixels, you’re tying those elements to the device the page is being viewed on. On a 96 DPI screen, text using a font sized in pixels will be shrunk to near unreadability when viewed on a 120 DPI screen. When printed to a device with DPIs in the thousands, the text would be tiny dots on the page.
However, I do not like using em because now those same elements are tied to the font being used. I would prefer using the generic names (small, medium, large, etc.) or points if absolutely necessary.
I totally agree with you on #7. Paddings are more consistent and help avoid the double margin bug.
When using the negative margin technique overflow:hidden will not work.Use instead clear:both or other similar techniques that don’t hide the content.
Nice article and +1 for using px instead of em
This is so clear and useful – thank you! I love your code tutorials,
very well written article…thnx for sharing such great information with us..
Nice article. Learned a few new things from that. It’s also nice to know that I already do a number of those!
Excellent read – thank you for the refresh!
7. Use Margins When Styling Layouts – from my experience with IE6 debugging it seams that working with padding instead of margins is doing a better job. Anyway there is great chance using display: inline (as you say on .9) to fix the problem not only for floated elements though.
Thanks buddy!
I agree, I never use margins, only when i have to, since IE6 will almost double any margin, and padding has always been the same for me across browsers.