10 Principles of the CSS Masters
Aug 25th in HTML & CSS by Glen Stansberry
When it comes to CSS, there are lots of resources and supposed "expert tips" on the web. These are from unproven, self-proclaimed "gurus" who have no street cred in the design world. While they may have valid points, how is one to know whether a CSS tip is a valid resource or just an untested hack?
Instead of relying on unknown sources for advice, let's look deeply into designers who have excellent design backgrounds and have walked the walk. These CSS tips are gathered from some of the most respected designers on the planet. They have the portfolios to back their advice up, so you'll know that each tidbit of advice is of the highest quality.
Below are 10 excellent principles that any web developer or designer can find useful, meaningful, or challenging. Consider this sage advice from journeymen (and women) who have walked the long, hard road of design excellence. These are the true masters of CSS. Drink deep from their knowledge and take their wisdom on your next designing adventure.
1. Keep CSS simple - Peter-Paul Koch
What bothers me most about the mindset of CSS hackers is that they are actively searching for complicated solutions. Seek and ye shall be found, if you want complexity it’ll take you by the throat. It’ll never let go of you, and it won’t help you, either.
Peter-Paul Koch is a godfather of web development. While he's an old-school developer and the bulk of his web portfolio was between 1998-2002, he's worked with the likes of Apple and other heavyweights. He's written a book on javascript, but don't think for a second he doesn't have anything to say about CSS.
The danger of CSS hacks
Koch has addressed something that every designer and web developer should follow with zeal: Keep your CSS simple. Simplicity is a hard thing to achieve, especially in CSS design. There are a myriad of CSS hacks that one can find for making all browsers look the same, regardless of version or type. Yet there's a fundamental flaw with using many CSS hacks. As web browsers evolve, it's much harder to keep up with the changes.
Koch makes an interesting point about developing for the web. The Internet as as whole is a very unpredictable place, and trying to second-guess the way it will work in the future is a very bad strategy.
The Web is an uncertain place. You’ll never be sure that your Web sites will work in the exact way you want them to work, not even when you apply all modern insights from CSS, accessibility and usability. Instead of seeking false comfort in hacks that seem all the more comfortable because of their complexity, you should accept uncertainty as a basic principle.
Browsers don’t have perfect CSS support; especially for people who’ve just started learning CSS, that can be infuriating. Nonetheless CSS hacks are not the solution. Acceptance of the way the Web currently works is the best way to go because it’ll keep your sites simple.
Peter-Paul has hit on something that rings true for not only CSS, but for web development as a whole. Simplicity is key for efficiency in coding.
2. Keep CSS declarations in one line - Jonathan Snook
Jonathan Snook is an incredibly popular designer from Ottawa, Canada who's made his name in web standards and design. He's spoken at prestigious conferences like SXSW and has published quite a few technical resources on design through Sitepoint.
One of Jonathan's tenants to coding CSS is to keep declarations in one line.
The second one may look prettier but it sure doesn't help me find anything. When looking for something in a style sheet, the most important thing is the ruleset (that's the part before the { and } ). I'm looking for an element, an id or a class. Having everything on one line makes scanning the document much quicker as you simply see more on a page. Once I've found the ruleset I was looking for, find the property I want is usually straightforward enough as there are rarely that many.
Jonathan goes on to give an example for single line declarations that looks like this:
Good
{font-size:18px; border:1px solid blue; color:#000; background-color:#FFF;}
Bad
h2 {
font-size:18px;
border:1px solid blue;
color:#000;
background-color:#FFF;
}
Not only does this approach help with quickly scanning your CSS, it also helps in keeping your CSS file smaller by removing unneeded spaces and characters.
3. Use CSS shorthand - Roger Johansson
Most people know about and use some shorthand, but many don’t make full use of these space saving properties.
Roger Johansson knows a thing or two about designing for the web. The Swedish web designer has been working on the Internet since 1994, and has a popular web design blog. When it comes to simple and elegant solutions, Roger is one of the most knowledgeable in his field.
Johansson has a very in-depth article on the importance of CSS shorthand, and gives quite a few examples of how to use it while coding CSS. Here's an example:
Using shorthand for these properties can save a lot of space. For example, to specify different margins for all sides of a box, you could use this:
margin-top:1em;
margin-right:0;
margin-bottom:2em;
margin-left:0.5em;
But this is much more efficient:
margin:1em 0 2em 0.5em;
The same syntax is used for the padding property.
While CSS shorthand reduces the size of the stylesheet, it also helps organize and keep the code simple. Beautiful CSS is simple CSS.
4. Allow block elements to fill space naturally - Jonathan Snook
Mr. Snook has another piece of crucial advice that every web developer should live by: allow block elements to fill space organically. If there's one recurring theme in CSS development, it's to not force the code to do things it isn't meant for. This means avoiding CSS hacks and finding the simplest solution possible.
My rule of thumb is, if I set a width, I don't set margin or padding. Likewise, if I'm setting a margin or padding, I don't set a width. Dealing with the box model can be such a pain, especially if you're dealing with percentages. Therefore, I set the width on the containers and then set margin and padding on the elements within them. Everything usually turns out swimmingly.
Jonathan's rule of thumb is great for ensuring that your layouts won't break and that the simplest approach is used when creating layouts with block elements.
5. Set a float to clear a float - Trevor Davis
Floating is probably one of the most important things to understand with CSS, but knowing how to clear floats is necessary too.
Trevor Davis may not be as big of a name as Zeldman or Snook in the design world, he surely deserves some mention just based on his excellent portfolio of web layouts. His blog is an excellent resource for any web developer wanting to brush up on his design chops.
Clearing floats
In Trevor's flagship article The 6 Most Important CSS Techniques You Need To Know, he's added a nugget that can save many headaches when using columns in your layouts.
I have created a simple page with two floating columns next to each other. You will notice in the example that the grey background does not contain the floating columns. So, the easiest thing to do is to set the containing element to float. But now, you will see that the container background doesn’t contain the content area.
Since the container has margin: 0 auto, we do not want to float it because it will move it to whichever side we float it. So another way to clear the float, is to insert a clearing element. In this case, I just use an empty div set to clear: both. Now, there are other ways to clear a float without markup, but I have noticed some inconsistencies with that technique, so I just sacrifice an empty div.
6. Use negative margins - Dan Cederholm
Sometimes it’s easier to deal with the exception to the rule, rather than add declarations for all other elements around it.
Dan Cederholm's company SimpleBits is a powerhouse of a design company. Dan's worked with the likes of:
- Google
- Blogger
- MTV
- Fast Company
- Inc.com
... and many other high-profile web companies. Fortunately, Dan passes on some of the knowledge he's learned working with these massive names on his blog at SimpleBits. Here's a rule of thumb for you web designers and developers: If Dan Cederholm says anything, you listen. Think of him as a digital sherpa, guiding you to the crest of your design mountain.
Negative margins
While it may seem counterintuitive to put a negative in front of any declaration (like margin-left: -5px), it's actually quite a good idea. Mr. Cedarholm explains that using negative margins on elements are sometimes easier than having to change every other aspect of the design to make it align they way you want.
There are situations when using negative margins on an element can be the easiest way to “nudge” it out from the rest, treating the exception to the rule in order to simplifiy code.
You can see his example of proper negative margin usage here.
7. Use CSS to center layouts - Dan Cederholm
"How do I center a fixed-width layout using CSS?" For those that know, it’s simple. For those that don’t, finding the two necessary rules to complete the job can be frustrating.
It's no surprise that Dan is going to make this list twice. Centered layouts are on the surface a very simple idea, but for some reason they don't always work as easily as advertised. Centering layouts with CSS can be a frustrating endeavor for a beginner if they've never tried it before.
Dan's got a tried-and-true method that he uses frequently to achieve centered-layout nirvana.
#container {
margin: 0 auto;
width: xxxpx;
text-align: left;
}
Many modern designs rely on centered layouts, so using this method will at some point come in handy for web developers and designers.
8. Use the right DOCTYPE - Jeffrey Zeldman
You’ve written valid XHTML and CSS. You’ve used the W3C standard Document Object Model (DOM) to manipulate dynamic page elements. Yet, in browsers designed to support these very standards, your site is failing. A faulty DOCTYPE is likely to blame.
Jeffrey Zeldman is one of the co-founders of the excellent resource site A List Apart, co-founded and ran The Web Standards Project, runs the Happy Cog design studio, and even wrote the book on designing for web standards. In short, Zeldman is in the upper-echelon of web designers.
DOCTYPE misunderstanding
The DOCTYPE of a web page is one of the most overlooked aspects of design. Using the right DOCTYPE is crucial, and Zeldman explains why.
Using an incomplete or outdated DOCTYPE—or no DOCTYPE at all—throws these same browsers into “Quirks” mode, where the browser assumes you’ve written old-fashioned, invalid markup and code per the depressing industry norms of the late 1990s.
Zeldman stresses the importance of a) actually using a DOCTYPE, and points out that you have to add an url in the declaration like so:
If you're finding unexplained problems with your layouts, odds are the DOCTYPE could be the problem.
9. Center Items with CSS - Wolfgang Bartelme
Centering items is a frequent task when designing websites. But for people that are new to CSS it’s mostly kind of enigma how to center for example a whole website in browsers other than IE.
Wolfgang Bartelme is a web designer with Bartelme design, a web design firm. Bartelme has one of the most elegantly-designed blogs, and continually creates excellent icon and design work. He's done design work for the blogging platform Squarespace, as well as the popular software event MacHeist.
Wolfgang has created a tutorial that helps with the complicated task of centering elements with CSS. Centered elements are insanely useful, but are sometimes hard to achieve given the design. Bartelme's tutorial ensures centered alignment by choosing the right DOCTYPE and making adding his CSS voodoo. The code nothing fancy and gets the job done, and falls directly in line with striving for simplicity in CSS.
10. Utilize text-transform commands - Trenton Moss
Trenton Moss knows web usability. He has his own web usability company that trains people in usability training and web writing. He also writes for sites like Sitepoint. Trenton gives excellent tips based on his experience as a web usability expert.
It's a simple fact that designs change over time, especially in the way text is displayed on websites. The best thing a web designer can do is plan for the future to make sure that instead of having to manually change the way text is displayed, it's best to use CSS to change the appearance of the text. Trenton Moss shows us how to achieve this through the use of a simple, underused CSS command called text-transfom.
One of the lesser known, but really useful CSS commands is the text-transform command. Three of the more common values for this rule are: text-transform: uppercase, text-transform: lowercase and text-transform: capitalize. The first rule turns all characters into capital letters, the second turns them all into small letters, and the third makes the first letter of each word a capital letter.
By using CSS to display the appearance of text on the site, it allows for change in the future and keeps things consistent over time.
This command is incredibly useful to help ensure consistency in style across an entire Website, particularly if it has a number of content editors. Say for example your style guide dictates that words in headings must always begin with capital letters. To ensure that this is always the case, use text-transform: capitalize. Even if site editors forget about the capitalisation, their mistake won't show up on the Website.
While text-transform is a small thing to add to add to a css layout, it can make a world of difference in the future when changes need to be made.
- Subscribe to the NETTUTS RSS Feed for more daily web development tutorials and articles.
Glen Stansberry is a web developer and blogger who's struggled more times than he'd wish to admit with CSS. You can read more tips on web development at his blog Web Jackalope.
User Comments
( ADD YOURS )Jeffrey Way August 25th
In reference to the “clear a floated element” tip by Trevor Davis - I would disagree. Setting overflow:hidden on the container element takes care of it. I’ve never had any problems. Or you can use the extended “containerElement:after” method to clear it.
BlueBoden August 25th
These Techniques are well known among most web designers, working with css based layouts.
The problem with float is that it is tricky to create multi-column layouts, this is where CSS position is much easier to work with, and of cause it shouldn’t require as much div-it-is as the float based layouts.
Vasili August 25th
I love numbers 4, 6 and 7 the most. Number four and I go back a long time.
Max | Design Shard August 25th
Some good points , i guess every one has there own ways of dealing with css, som better than others.
Jeffrey Way August 25th
Here is a brief snippet from a SitePoint article that details the method I’m speaking of (overflow: auto, overflow:hidden) to clear a child element that is floated.
“…until last week when SitePoint Forum’s own CSS Guru, Paul O’Brien, nonchalantly pointed out that adding a ‘overflow:auto’ to the outer DIV did the trick. [clearing the floated element]
‘Rubbish’ I thought to myself.
Half an hour of testing later, I was amazed to find Paul was 100% correct - as this example shows. It seems that reminding the outer DIV that it’s overflow is set to ‘auto’, forces it to think “oh yeah.. I’m wrapping that thing, aren’t I?”.
This fact is so boringly simple that it’s hard to know if thousands of developers are well aware of it, but never thought to mention it. I know I showed the example page to four CSS-savvy SitePoint colleagues and all shock their heads, blinked slowly and said “Whaa…?” (or something similar).”
Jay August 25th
Thank you Jeff.
PureDezigner August 25th
Very help post, also I’m digging the artwork you used to convey the message in each of the principles. Time to update my code structure on my website.
Dan August 25th
I’ve been setting up my CSS like #2 says for years, but never thought anyone else did. I’ve always wondered why people do it differently- this is a breath of fresh air.
oisean August 25th
Underwhelming stuff.
Simon August 25th
Jeff, that is unreal. Never knew it existed (it’s sooo simple), but goddamn I’m glad I’ll never have to type (or something similar) ever again.
insic August 25th
great tips. i like the article
Simon August 25th
Hmm can’t edit my comment, but oisean, I think there is a point where css/html tutes/articles become rather mundane. You’re not really going to find any new/exciting techniques other than the odd little pearl of wisdom (like Jeffs comment).
oisean August 25th
Simon, sure. I suppose this post suffers in comparison with yesterday’s PHP tut.
begs August 25th
“Keep CSS declarations in one line - Jonathan Snook”
I don’t agree here. It’s awful to edit one lined CSS declarations.
Readability and of course editability for me as develpoper is much more of weight than the size of the css file.
Tab and multiline your CSS declarations. Everyone can then edit the file easyly, and also find the right declarations fast. (And if not, they can use STRG+F / APPLE+F)
And the fact, that a CSS File is much smaller, if there were no whitspaces in it, is true, but if you use images on your page with 100Kb (like in this article) no one cares about 1-2 Kb smaller CSS Files.
Simon August 25th
oisean, indeed
oisean August 25th
Agree with begs.
Blaž August 26th
Nice article for beginer like me :). Time to change some code on a page that I am working on :). Oh and thanks Jeff, your method is to simple to be true.
Niklas August 26th
Once again you guys open my eyes to new blogs and new websites! The article talks about interesting ideas. Even though I don’t agree with all entries new ideas and thoughts is always nice to read about. Thanks for another great, inspiring, article!
Shane August 26th
Interesting list - thanks for posting.
James August 26th
@BlueBoden - Creating a multi column layout does not have to be hard with CSS. Have a look at some of the examples here: http://www.pmob.co.uk/
I liked and agreed with most of the points made with the tutorial. I have to agree with Jeffrey’s comment on the whole clearing floats issue.
I can see where Mr Snook is coming from on his, “keep declerations on the same line” rule but seriously, the only benefit I see in doing this is saving a bit of space. I cannot quite understand how the CSS file is more maintable if you do this. Surely a CSS file will be easier to manage with the traditional CSS decleration pattern:
element.selector {
property: value;
property: value;
property: value;
}
I can see how scanning a document might be faster with Snook’s approach but an entire ruleset can get quite lengthy and ends up being ugly in the text editor if it wraps (and harder to look at and add to or take away from) - and if it doesn’t wrap - like in Aptana
- then you’re left with horiztonal scrolling which I hate!
I like what Snook says about letting block elements fill space naturally… Too many people feel that they have to define a width for everything!
Anyway nice list, thanks Glen!
Ben Griffiths August 26th
This was a great post - although I agree about the one line method, I hate that style
Raul Pedro Santos August 26th
I also have to agree with begs.
Having a CSS rule in just one line is confusing as hell. It may seem simpler but studies have proven a long time ago that, when looking for something, it’s easier to scan vertically along the first letters of the text, than it is to scan horizontally. And it’s quite simple to understand why, too. If you scan vertically, you just need to read the first couple of letters to know right away if that’s what you’re looking for, while when scanning horizontally you have to go through all the text because you can’t see as easily where a declaration ends and the next one starts. Scanning vertically allows you to look *immediately* at the beginning of each declaration.
If file size is crucial, then you can always use a compressor on it, to remove extra white space and unnecessary newlines. But only when deploying the site; I would never work on a CSS file like the article says to.
Jayphen August 26th
Nice article, though I don’t agree with #2 or #5.
#2
This simply looks a mess, in my opinion. Properly commented, sectioned & tabbed CSS beats having everything on one line any day, especially if you have more than one person editing a CSS file. If your problem is trying find a selector, a simple ctrl-F search will find it instantly (assuming you know the name of the ID or class, but why wouldn’t you?). If you have a lot of properties and values on the same line, it is difficult to find exactly what you’re looking for among them, and you can’t as easily ctrl-F and search for what you’re looking for, as it will undoubtedly appear many times throughout the entire CSS document.
#5
As mentioned before, overflow:hidden on the containing element is a much more elegant solution to this problem.
Gafroninja August 26th
I have to say, I partially disagree with Jonathan Snook on point #2.
I think its wrong to say not using single line declarations is “bad”. I believe its more preference since there is almost no gain in file size. Some people find it easier if the declarations are over multiple lines some find it easier if it’s over single lines.
I use both. Any element that has less than 3 declarations, i use single line. If any more I use multiple lines.
Other than that, these are all good.
Just my view not a hardcore fact or standard.
insic August 26th
Keep CSS declarations in one line? i dont think so. for me, it makes your stylesheet horrible to read. im not againts with the masters, its my own idea only. hehehe
Ryan August 26th
> “Keep CSS declarations in one line - Jonathan Snook”
What nonsense, this is nothing more than personal opinion so shouldn’t be listed as some sort of definitive rule. Single line declarations can become very hard to read, indenting and setting decelerations on individual lines is good for the same reason it’s good to correctly format PHP, JS, Python, HTML etc… but as I say it’s personal choice and the one line approach is certainly not *the* best.
Ryan August 26th
Also I’ve not used empty clearing divs for years, there’s no need to add useless markup since the solution can be accomplished for more efficiently through CSS. The CSS approach is also far more flexible if you decide to change the layout.
oisean August 26th
So we all agree that single-line declarations are a good idea, then?
Iain Edminster August 26th
I’m glad to see other people disagreeing with “Keeping CSS declarations in one line”. This “rule” is more like personal choice. If you are working on a website with other people, doing things like this would be counter-productive. I’ve found the best way to write CSS is to separate key declarations into separate files contained in a single folder and then gather them all, compress it and cache it. Same thing can be said with Javascript files.
FlyboyArt August 26th
While I admit it’s harder to edit CSS if it’s on one line, it truly saves some space and time in downloading. If you ignore all these 1k here, 1k there things then you’re website will become bloated. To be truly efficient, run your CSS file through a compressor (like we do for JS files) before you send it along to your website. Edit it in any fashion you want (one line or many) but at least upload it in the most efficient format for downloaded by browsers. They don’t care how it looks, just that it’s formatted properly.
My two cents… ;=}
Anthony Short August 26th
I should point out that with #4, you really shouldn’t have box model issues unless you’re accounting for IE5.5. IE6 renders the box model fine if its in strict mode. Add widths, margins and padding to whatever you want, you won’t break it in IE6+.
shubox August 26th
#2 Snook’s idea of keeping CSS in one line? I’ve heard this before and disagreed with it then, and disagree with it now. I have never noticed any file size difference or performance difference when using inline vs multi-line method. And in terms of ease of editing, the multi-line method is startling easier to look at and identify each part. Inline might work for Snook, that’s fine - but is certainly NOT bad practice to use multi-line layout for css.
Dan Harper August 26th
With most of the other comments, I completely disagree with keeping declarations on one line. Although, it’s really just personal preference and everyone develops their own way of laying out a document.
Philo August 26th
Nice Article!
Joris August 26th
I agree on most of the things although I’d never use negative margins for a standard, they don’t always come out correctly and I only use them as a ast resort.
As for the centered content I used to love it but after reading some usability studies etc I changed my mind, same goes for centered navigation, like underneath the header for example.
Ben W August 26th
No, no no. I really can’t handle CSS declarations on a single line - someone I work with does that and I find it takes me MUCH longer to edit their CSS files. Also their CSS is always a complete mess with many duplicated ids/classes/attributes.
I find it best to indent like this:
#someid {
background: #FFF;
border: 1px soldi #CCC;
font-size: 1em;
}
Then it’s very easy to scan down the left side and find what you need. Attributes should be in alphabetical order too.
Other than that - good advice - nothing new though (to me).
BTW in #8 you say “Zeldman stresses the importance of a) actually using a DOCTYPE, and points out that you have to add an url in the declaration like so:”
Like what?
Looks like you omitted the example.
Ben W August 26th
Damn - looks like my indenting got “parsed out”. Bah!
OK - in my CSS declaration, each attribute and the closing brace should be indented to line up with the opening brace (plus an extra space or two).
Web Designer August 26th
Thanks for this!
Dan August 26th
I prefer indenting than putting everything one one, RE one line css.
I don’t like having to scroll to the right to read my rules.
If you indent properly you get the same effect of being able to scan read the selectors.
And of course, you can always add comments to remind you what everything is.
Alper August 26th
Thanks for Article!!There are some good points that every css master’s should take care
Dan August 26th
Good comments going on here
Ian Stewart August 26th
For what it’s worth, I didn’t know about overflow:hidden for clearing floats until I read Transcending CSS.
Also, one line CSS = crazy talk.
Jeffrey Way August 26th
I suppose I should weigh in on the CSS one line discussion. I, personally, prefer the vertical method. However, it is true that your file sizes will be larger this way. To compensate, I always run my stylesheet through a compressor just before deploying a project.
Wayne August 26th
Single line declarations? Bah. Keep it readable, dude.
S.K August 26th
One fun alternative to float layouts is the inline-block property. A couple of advantages I can think of right now include being able to use the vertical-align property and no float bugs. Just remember to unclude display:inline in your IE stylesheet.
David Parker August 26th
Like many other said, #2 is bunk. Keep your declarations on multiple lines and tab them. Also, if you’re worried about space, then run your CSS file through a script to remove all whitespace before you deploy. Best of both worlds.
Nate August 26th
Good article.
Kevin Quillen August 26th
I think #2 is completely and utterly wrong. Single line formatting only makes things that much HARDER to find the rules you are looking for. Tab indentation makes reading more easier. What if your PHP/CF/ASP applications were all on a single line?
In a business environment, that rule must be expanded upon to a level of consistency wherein coworkers follow the same style of formatting… example, reference with absolutes like div#container, instead of just #container. With that, the CSS sheet should follow the markup of the document, i.e. footer not being delcared at the top, header in the middle, etc.
This rule really only works within your own work. When a CSS sheet grows to 1000 lines, its very difficult to filter visually for what you are trying to find.
Aaron Irizarry August 26th
Thanks for the article… good brush up, and good to compare views on techniques.
thanks!!!
Michael Thompson August 26th
Real CSS masters have a text editor (eg., Vim) capable of folds; making the declarations appear on one line until unfolded to reveal multi-line style definitions.
I’d like to up the ante on this debate by quoting Roger Johansson from his blog post, CSS Tips and Tricks, Part 2:
“When I combine selectors, I normally put them on separate lines. I find it easier to find things in the CSS file that way. Next, I leave a space between the end of the last selector and the opening brace. Each declaration goes on a separate line, with no indentation and no spaces around the colons separating properties from values. … Finally, the closing brace goes on a line of its own.”
The style that CSS is written in is purely personal, and a rule imposing one person’s preference should never have been included in this article. Otherwise, good article.
Paul Gendek August 26th
I don’t agree with Johnathan Snook either.
It’s called Cascading Style Sheets, they should be cascading.
If it isn’t easy to scan through, then you didn’t organize it very well. Obviously an optimized stylesheet is best for dense CSS on production sites but I find that keeping my CSS organized and cascading by nested elements works best… for organization and ease of readability!
Jason August 26th
I used to be a multi-lined CSS person. I have just recently changed to single-line and personally love it. There is nothing less readable about it and it makes finding the one you’re looking for fast and easy. If you find yourself tinkering with your CSS a lot multi-lined may be easier but I usually don’t have to. Using the single lined method has also removed the need to comment different sections of my style sheet. Do two sites with single-line declarations and you’ll probably never go back to pressing enter and tab after every attribute.
Andy Ford August 26th
#2 is just bad practice and makes for a very difficult to read/scan file.
I will say that if a css declaration block has only one property in it, then I will usually format it as one line. But as soon as there are 2 or more properties, then I put them on separate lines.
The extra few KB you’ll save by putting each declaration block on one line just doesn’t pay off in my opinion.
If bandwidth is a concern, then you’ll probably just want to use an automated css compression tool for your production css file.
Erik August 26th
Beyond just the concept of readability, there are other aspects to consider when evaluating tip #2. Those being, the usage of source control (SVN, Git, etc.) and being able to cleanly track diffs throughout development. Having all of your declarations on one line effectively kills any method of tracking minutia changes.
As many others have stated before, its far more sane to leave your rules on multiple lines and skip premature optimization (letting an optimizer do the heavy lifting at deployment time).
ron August 26th
#2 is really stupid.
first, theres this handy thing called the tab key which indents the rules for an element so the element names stand out for quick scanning. really, there is!
second putting all the rules in a line often wraps the line thus destroying the stupid reason you did it that way in the first place.
third, now that you so smartly put every rule in a line, how easy is it to now scan the rules themselves?
and if you’re so concerned about saving the huge amounts of wasted bandwidth that result from spaces and tabs, you’d use one of the CSS compression tools.
Jason August 26th
@Paul - I think the cascading refers to the properties, not the layout of your document.
@Michael - There are hundreds of ways to skin a cat, and seeing that this article is titled “10 Principles of CSS Masters” that means that these are the ways that these guys that are considered experts prefer to do things. One of them could have easily have been use external style sheets - but that kind of goes without saying because we ALL subscribe to that principle. Another would be using browser conditionals and separate style sheets to make sure those CSS hacks don’t come back to bite us when future browsers are around. We probably all subscribe to that theory as well so including it in this list is pointless.
In the end, you have to throw something debatable in there to get the conversation started.
Arnaud Talaia August 26th
Maybe it’s just me, but I would totally disagree with having the code written on one single line..
Yes, it does save space and coding lines,
YET
reading is sequential and, much in the same way that comas will help make a sentence a little easier to be heard by puting a sound gap between two ideas, writing bunches of code in deifferent line, helps understand the architecture of the code.
To me that one advice has definitely been writen by one tech-guy for another tech-guy : not common (and humble) people !
Coding space is cheap, if it helps to make the code look clearer : use as much of it as you’d like ! That would be my advice..
ren August 26th
I don’t agree with you about the one line declarations. It is very sloppy coding. We should share our CSS code by making it as easy to read as possible.
td
{
background-image : url(transparency.png) ;
color : ffffff ;
font-family : “Journal” ;
font-size : 25px ;
line-height : 30px ;
padding-bottom : 30px ;
padding-left : 30px ;
padding-right : 5px ;
padding-top : 5px;
vertical-align : top ;
}
Josh August 26th
I don’t care for #2, just compress your CSS. The rest are all very good. I will have to share it with everyone at work. Thanks!
KangarooDeziner August 26th
I’ll add my two cents as well, I suppose.
I’m also going to have to agree with #2 here. How you write and read your CSS in the terms of one line or multi-line isn’t something that needs to be set in stone. There is no “right” way. Both have their advantages. Personally, I’ll use the multi-line way, because I work with a team of developers and we’ve all agreed that’s the best way to go about it for readability purposes.
For number 3, this is a good idea, but there are very few sources that show how to use CSS short-hand effectively.
http://www.dustindiaz.com/css-shorthand/
I think this article has great examples of how to do shorthand correctly. You have to be careful when you write shorthand, there are very specific orders. Most of us know TRBL, but not many will know the exact order of Font.
http://www.456bereastreet.com/archive/200502/efficient_css_with_shorthand_properties/
This article also has good tips.
For number 5, I’ll have to agree with the people who posted the overflow: auto/width solution. Adding a clearing div isn’t semantic markup. It’s presentational as opposed to structure. There may be times where this doesn’t always work, but believe me, I’ve come across times where this is the only method that does work, because a clearing div does not stay consistent between IE 6 and IE 7. It’s good to know multiple ways to solve a problem, and use the solution that fits for that scenario.
As for number 7, you’re forgetting an important part of the method there.
“#container { margin: 0 auto; width: xxxpx; text-align: left; } ”
This does not center a layout in IE. To center the layout in IE, you need to add “text-align: center” to an element that wraps around container.
And I’m not sure how 7 differs from 9. The principle is the same. You’re centering an element. I’m not sure it needed to be on here twice.
And for number 8, it seems there’s an example that may be missing. It says “add an url in the declaration like so:” but then doesn’t show an example (at least not that I can see).
Kevin Quillen August 26th
It’s still stupid because you are thinking from first person perspective. The way youformat your documents should be agreed upon within your working environment. We have multiple people working on layouts so we need to be as friendly and readable as possible so anyone can jump in and figure something out. It takes longer to read single line.
Real CSS Masters using VIM is just a geeked statement. Anything you can do editing in gets the job done, from Notepad, to Notepad++ (me like) to Dreamweaver. So long as the code is written.
Dino August 26th
Nice tips! I’ve been using rule#2 for almost 5 months now and I can say it made my work faster and simpler. Plus it’s a lot easier to find errors.
BTW, what’s with the Japanese drawings?
Ericka Wright August 26th
@Jeffrey Way: I was just curious if you are able to make overflow:hidden or overflow:auto work with a PNG fix for IE6 such as: http://www.twinhelix.com/css/iepngfix/ or http://labs.unitinteractive.com/unitpngfix.php ? I’m afraid I’m not clever enough to write my own code to fix the IE6 PNG problem and when I tried using overflow:auto and overflow:hidden to work with the fixes, it broke the layout badly.
Jared August 26th
I agree #2 is just a huge waste of time. I work with a guy who started writing his CSS that way, and as just about everyone else has said so far, multi-line tabbed CSS beats single line any day of the week
Carlton Dickson August 26th
I don’t think putting CSS declarations on seperate lines should be labelled as *bad*. The chosen method should ultimately help the CSS developer(s) organise declarations in a clean way, that is easy to work on and is maintainable for future updates…the only downside for me is the file size but you can easily run the CSS through a minifier if you’re worried about that.
Personally I use single line declarations but prefer to put the properties in alphabetical order.
I know other developers that use multiline declarations and indent code which also helps organise things and is quite a good way of structuring CSS.
Jeffrey Way August 26th
@Ericka - I’ve never had any problems. But, if the overflow method isn’t working for you, you can try the alternative.
#elementWithFloatedChild:after
{
visibility: hidden;
content: ".";
height: 0;
display: block;
clear: both;
}
This will work too on modern browsers. To compensate for IE6, which doesn’t support “:after”, set a height value to the container element. IE6 incorrectly reads “height” as “minimum height”. Consequently, it will expand to fill its contents. Hope this helps!
Nathan Smith August 26th
The #2 tip is a matter of preference, not a recommendation of best practice. In fact, I would go so far as to say it is erroneous. I have run into problems with people writing all their declarations on one line, increasing the likelihood of errors. In general, if a horizontal scrollbar is bad in web page layout, why would anyone permit a horizontal scrollbar in their CSS code? As for file-size savings, you could always use a CSS compressor…
http://www.cssdrive.com/index.php/main/csscompressoradvanced/
That being said, the other 9 tips are right-on.
Andi Kalsch August 26th
- Rules 7 and 9 are the same.
- Rule 2 makes no sense because editing and overviewing defined styles for a rule is important, too. There are other ways to find rules quickly. E.g.
h2 {
rule;
rule;
}
This is better for me and dynamic server side CSS compression is another solution to make your pages loading quicklier.
- Rule 1 is the most important. Keep it simple. CSS is just a way to style your content. Most important is the content. Don’t use ugly hacks that will have to be removed, when the next browser version is coming up.
The techniques you describe are well-known among web designers and were not “invented” by single persons. So I really ask myself if I am a CSS master now (???)
Michael August 26th
I have to disagree with #2. In the 10 years I’ve been designing and developing web sites, it has been my experience that dividing the CSS across multiple lines makes it far easier to maintain.
Often times its a matter of preference to be sure, but you also need to keep in mind the next person who has to come along and maintain your code. And as was already mentioned, the file size savings are nearly unnoticeable. Far better to have easy to maintain code than to try and save a couple of KB.
Create a coding style guide and stick with it. This not only helps others who may have to maintain your code, but can also be a benefit to you. If your code is styled in a standardized way, you and those you work with, can much more easily find what it is that you or they are looking for.
Also, don’t be afraid to use comments. Commenting your code, whether HTML/XHTML, CSS, JavaScript, PHP, Ruby or what have you, can be a HUGE benefit when you come back to do some work on it weeks or even months later. It makes it much easier to understand why you did things a certain way, and with the knowledge you have gained in the intervening time, you may just be able to make that part work a little better.
andi August 26th
Does anyone have any objections to #2 - I haven’t read any.
Well except the first two thousand.
Miles Johnson August 26th
This statement is not entirely true “Not only does this approach help with quickly scanning your CSS, it also helps in keeping your CSS file smaller by removing unneeded spaces and characters.”.
Ive written a CSSMinifier PHP script that strips all whitespace/comments and anything else not needed. It took a 190k file and made it 180k. That is not a big difference at all and nothing worthwhile… and in its place you get a giant css file on 1 line, for what… 10 measly k?
Vaçlav Rant August 26th
Great post! I am not too sure about a few things though, I think you miss a few important principles and techniques Eric Meyer — http://meyerweb.com/eric/thoughts/ — and Jens Meiert — http://meiert.com/en/blog/categories/web-development/ — describe…
Amy August 26th
Pretty good article, not a whole lot of new info but good for reminding you who you should be keeping tabs on in the web world.
Regarding Snook’s most controversial quote: I do a combination of 1-line and tabbed-multiline css declarations… basically if I’m adding one property I will do it single line because I hate having to enter+tab for just one property, not to mention it’s not hard to read. Anything more than just one property gets broken up into multiple lines most of the time. I don’t worry about ease of scanning because I utilize the Find & Replace feature on my editor. I think some CSS gurus are SO efficient that they probably don’t need to go back into their code too much (so the 1 line declarations would be appropriate), but for me, I still do a lot of experimentation.
I’m really interested in trying out the overflow:auto in lieu of empty clear elements. It seems to make a lot of sense and would make me feel a whole lot less guilty!
James August 26th
@Miles - I agree with you but 10k can become quite a significant amount, especially when developing for mobile sites.
John Deszell August 26th
All good tips I think.
Though I don’t and don’t like writing all my CSS in one line. For me it’s harder to read and just doesn’t seem right to me. The amount of file size saved is super slim if much of anything. Maybe 1 or 2k at the most (and thats on a HUGE site).
Jen Germann August 26th
Great article. Everyone has their own way of doing things and some of these tips are better than others. Actually, your comment from Sitepoint about the overflow:auto trick is probably the most valuable part of the article, for me.
Matthias König August 26th
Nice article, but i don’t think that points 2 and 4 are good ideas…
Point 2: The Code might look “smaler” when you write everything in line, but it’s much easier to find mistakes when the attributes are NOT in line, i think.
Point 4: Doesnt help keep the CSS clean, doesnt it?! For example:
I have a container (Content) with all the things in it (headlines, p’s, img’s, ul’s, a’s, etc.) - why give every object the same margin or padding instead of giving it only to the container?
2nd possibility: often i have a Content-Container with 2 Coloums in it (”left” an “right”, floatet). But there will be some Pages (f.e. Contact) which won’t use the coloums. When i delete the 2 coloum-divs, the padding/margin of the container helps to hold the Contact-Content where it should be.
Much easier than give hundrets of objects the same padding/margin…
sean steezy August 26th
I didn’t realize that:
1. One comment from a “CSS master” would spark like 80% of the comments on here
2. That its a big deal to some people
3. The hide overflow thing. Thats sweet.
Thanks for the post. CSS is something that I learned from doing a lot of and some stuff I never bothered to try b/c it didn’t seem to do anything. Sweetness.
Fave up has the bomb diggity CSS sites to checkout.
PS: I create a section of my CSS for one-line declarations for small things like text colors, sizes, and fonts, etc. and then the main stuff like containers and such are on their own separate lines…. take THAT!
Jonathan Snook August 26th
@sean steezy: yeah, apparently multi-line declarations is like a religion. To further fuel the fire, you can even see what my code actually looks like:
http://flickr.com/photos/jonathansnook/2800852816/
I have a system and it works great for me but I have no intention of forcing it on anybody. If people don’t like it, fine, but for me, it helps me get the job done faster and easier. And as many people have said in other threads, it’s an easy search and replace to get multi-line declarations back.
AD August 26th
I completely disagree with number 2.
This goes against any readability principle used for other languages or for any written document.
The size of your css files doesn’t matter when you work on them. If you are looking for performance, some utilities can compress your css and javascript files before you deploy.
Readability is also not an issue. If you are a serious developer, you use a text editor with syntax coloring, so you can easily browse through your declarations, whether they are one line statements or multi-lines statements.
James August 26th
@Snook - Like I said in previous comments, I can see where you’re coming from and I have to say that your code does look quite manageable - but I still prefer the traditional way. Plus, don’t you hate having to scroll horizontally??? (But I guess u can wrap)
I can also see how it’s easier to scan the document and find a specific selector but it becomes hard to scan through all the individual decelerations.
As far as I’m concerned it’s the same deal when using JavaScript:
var object = {property: value,property: function() {doStuff();}}
There is no way that the above is more readable then this:
var object = {
property: value,
property: function() {
doStuff();
}
}
James August 26th
Eh Oh!!! … My tabs were lost in the post above… Gawd, okay - with underscores instead:
var object = {
____property: value,
____property: function() {
________doStuff();
____}
}
Jerry Chen August 26th