Write Better CSS With Best Practices
218Everyone has a slightly different approach to CSS. That’s part of the reason it can be a nightmare to edit someone else’s code.
But there are a few good practices you can use in your CSS to make your stylesheets easier for you to read, and easier for anyone else that ends up modifying them in the future.
Single-line vs. Multi-line
The first decision you’ll have to make in your CSS is whether you want to write it on multiple lines, like this:
.title { font-size:14px; line-height:20px; color:blue; } |
Or on one line, like this:
.title {font-size:14px;line-height:20px;color:blue;} |
When I started out, I began with the first method. By spreading the different CSS properties out onto different lines, you make them easier to read. That’s a great help when you’re still getting used to CSS.
As I got more confident with CSS though, I swapped to the second method.
Once you’re comfortable with CSS, the biggest time waster becomes finding the element (the .title part) you need. When you’ve split every property into its own line, the file becomes very long and unwieldy. I find it easier to scan down with the second method.
The file size is quite dramatically cut down (more on that later).
Of course, a lot of people will disagree with me there! This choice comes down mostly to personal preference. If you’re happier with one over the other, then go with it.
Section Your File
Like I said above, one of the biggest hassles of working with CSS is simply searching for the line you need to edit. To help with that, it’s worth dividing your file up into sections.
For example, you could have a “header” section for all the rules relating to the head of your page. Then when you need to edit your slogan, you know where to look. A simple comment above each section is all you need:
/*** Header ***/ |
Start With a Reset
Every browser applies its own slightly different styles to elements by default. The idea of a reset is to take away all of the styles a browser might add. It helps a great deal when it comes to browser inconsistencies.
A reset can be as simple as adding this at the start of your stylesheet:
* {margin:0;padding:0;} |
Or if you want a more comprehensive reset file that will cover everything, check out Eric Meyer’s CSS Reset.
Use Shorthand CSS
Shorthand CSS is simply combining a few related rules into one. Let’s take an example to see why it’s useful.
For example, if you wanted to set a blue background with an image in the top right corner, you might normally do something like this:
.example { background-color: blue; background-image: url(images/blue-bg.jpg); background-position: 100% 0; background-repeat: no-repeat; } |
But this could be combined into one simple rule:
.example {background: blue url(images/blue-bg.jpg) 100% 0 no-repeat;} |
It can take time to get used to the order of things in a shorthand rule, but once you do, they become second nature, and the advantage is clear!
You can read more about what shorthand CSS options there are at Dustin Diaz’s site.
Multiple Classes on One Element
This is often an unknown aspect of CSS, but it’s possible to add as many CSS classes to an element as you want.
The reason to do this is that you can define generic CSS styles that can be applied to a number of elements.
Let’s say you set up CSS styles for positioning and for info, then you could do something like this in your HTML:
<p class="info left">Some example text in your info paragraph.</p> |
That way the paragraph gets the appearance of an info paragraph, and you don’t have to redefine the styles for aligning it to the left.
Positioning Header Elements is Easy
In most sites, the header is a set width and a set height. With the rest of your page, the height changes depending on the content within (Long pages of text = longer pages), but with the header, the height never changes.
That means you can use absolute positioning for everything in your header. Positioning is one of the harder parts of CSS to wrap your head around, and the tendency at the start is to learn one way (e.g. floats) and just make do with that.
Let me give you can example of why absolute positioning is worth learning:
#header {position:relative;width:960px;height:120px;} .logo {position:absolute;top:20px;left:20px;} .slogan {position:absolute;top:70px;left:20px;} .searchform {position:absolute;top:20px;left:600px;} |
And in 4 lines, you’ve positioned every part of your header. It doesn’t get easier than that. That’s how I lay out every header I code.
Don’t Worry About Ems
There are a few different units of font measurement in CSS. Pixels, “em”s, and percentages. Ems and percentages are a way of laying things out relative to the line-height.
An old piece of advice was always to use ems because certain browsers (Have a guess which one…) couldn’t resize pixel fonts. That was a major downfall for building an accessible layout for users who need larger font sizes.
Nowadays though, any modern browser can work with pixel fonts (Because most of them use zooming now, instead of just making the fonts larger).
Pixels are much, much simpler to work with in your CSS. And given that they work every bit as well as ems now, there’s no need to complicate things.
Unordered Lists Make Things Easier
Again, this was something I didn’t pick up on until I’d worked a lot with CSS. You’ll start out by thinking of HTML unordered lists as a way of listing bullet points, but in reality, they’re a great way of marking up any sort of “list” content.
Aside from unordered lists, what about the navigation bar in your header? Or a set of subscription options after a post? Or the elements in your sidebar?
With your HTML well marked up, you can easily apply styles to all of the parts of your “list”, e.g. for your sidebar:
ul#sidebar li {margin: 0 0 20px 0; border:1px solid #000;} |
Use Comments
Comments are a way of adding some explanations to your code. Thankfully, most CSS is self-explanatory and you won’t need to worry about commenting extensively.
You should however use comments for any tricky parts whose purpose may not be immediately obvious. For example, if you added an extra rule or two to make sure things worked in IE, you might want to add a comment saying why those rules are there.
Stay Consistent
A lot of the things we’ve talked about come down to personal style and choice. Once you’ve made your choices though, you should make an effort to be consistent.
If your style constantly changes from one project to another, then when you go to edit the file again in 6 months time, you might find it a headache even to work with your own code now!
On top of that, if you stick with a certain approach for a while, it gives you time to really try it out and see if it works for you (e.g. if you swap from multi-line CSS to single-line, I can guarantee your next project is going to be harder than normal. But in 3 or 4 projects time, you might find you’re faster than ever before!)
Minify Your CSS
When you’ve finished laying out your CSS in the most human-friendly way possible, it’s time to think about the machines.
If your file is smaller, it’s going to download quicker. How do you make it smaller? By cutting out all of your comments and whitespace. You keep the human-friendly copy for you to edit, and then use the machine-friendly one as the actual file to be downloaded.
For a simple tool that takes care of this, check out Minify CSS. For a more complex tool, have a look at the YUI Compressor.
It’s up to you whether or not you want to do this. The advantage is faster loading times, but the disadvantage is that it’s a nuisance and you have to redo it every time you update your CSS (Also, if you’re doing it for a WordPress theme, you’ll need to add the theme info comments back in each time).
For those reasons, I don’t do this all the time. For clients who want to make slight CSS edits themselves occasionally, this is usually a big no.
Even for my own site, I already use single-line CSS so running my stylesheet through the minify tool above gives a 7% reduction. That’s about 1kb. It’s not worth the effort there.
How Do You Write Your CSS?
The tips I’ve given above are all to do with how I write my CSS. Do you have any other tips you’d like to share? Or disagree with anything I’ve mentioned? I’d love to hear it in the comments!
Of course, if you’re working with a CSS framework, your standards are going to have to align with theirs. There are a lot of good frameworks out there, so take the time to find one that you can work with easily. Check out this list at 1st Web Designer for an overview of several different frameworks.
Enjoy this post? You should follow me on Twitter!
Nice post, thanks for sharing.
– couple of items that I prefer, coding on multi-line instead of single line for readability
– shorthand properties whenever possible to reduce file size
– code commenting and group when possible.
Thanks for sharing your thoughts Thomas. I know plenty of people prefer multi-line CSS, nice to hear from someone from the other camp! :)
i thinks this is like other template
Great Post! Thanks for sharing with us! Very helpful
Yeah i like the shorthand, but the best comment here is about the comments, really important when you are dealing with css files which get passed around between different members of a team!
Until now I used Ems instead of pixel for the reason you mentioned, but now I’m going to switch back to pixels to improve rendering.
I would also add that it’s better not to chain more than 2 selectors in each CSS definition, because it slows down the rendition.
Instead, adding a class or an id to the inner level elements is better.
For example, instead of #sidebar ul li a{}, use #someID a{} (the someID is an id that was assigned to the specific UL element).
Useful post, thanks
That’s a good tip about the selectors Omer. It’s definitely something I’m guilty of though. Far too often I have lines using 5 and 6 selectors. It saves me from adding new classes altogether, but it definitely hurts the legibility of the stylesheet :(
Excellent post, the point about not using em’s is what really got me excited… I have been using em’s for such a long time that I never wondered if this was still necessary. Using px is definitely much easier so from now on I shall stop using em’s :)
Glad to hear the post had a good influence for you!
It’s definitely safe to leave them behind now. IE6 is the only browser that doesn’t handle them well, and I’m of the opinion that if someone has accessibility issues or knows they have poor eye sight, they should have made the effort to upgrade their browser by now (Or their company upgraded it for them at work).
Where exactly would you put the CSS Reset rules? Before any style rules?
Yes, it’s right. Reset CSS should be placed before any other rules.
In addition, I’d like to alphabetize my CSS properties. It’s just personal style. A bit harder (and slower) when coding, but it’s easier when we need to find where is the property.
Yep, Rilwis is right here! That way any rules you place further down the page will overrule it. Let me know if you’d like to see a more in-depth post on resets here and I’ll be happy to do it! :)
@Rilwis – That’s a cool idea. I’ve never done it before, but I can definitely see why it would be handy when you’re scanning the rules later! I take it that means you also write on multiple lines?
@Michael Great post, I have an issue with the alphabetical order though as it’s a lot faster to create your own order. For example, border (if alphabetically) would go somewhere in the beginning but with CSS3 border radius, there will be a lot of junk in the beginning. I also like to keep some things together, like margin and padding, and width and height. Also if something has a different display value like none, I want to make that clear and put it first.
I like to code in single line, as it allows for easier scanning, coding, and saves up space. Sometimes I don’t like to compress my CSS, ’cause if I use the web developer toolbar, it’s all in one line.
Shorthand is definitely useful, especially for margins, padding, and backgrounds. Oh and multiple classes, depending on how they’re used, are a big help too.
I like the part “Positioning Header Elements is Easy”. its a new idea for me as i usually use margin or line hight to horizontally and vertically align elements in header.
I am not sure how much people will agree with you idea of leaving em or percentage for font-size, but i wish we should have a single and simple thing like px to specify.
Overall really great post. Keep up the good work.
Thanks Saqib, it’s really nice to hear you found the post helpful! I can’t remember when I first started doing headers that way, but it’s definitely my favorite part of a website to code now! :)
Any chance you could share your thoughts on why not to leave ems? I didn’t give an overly long justification above, but the reason for me is just that IE6 is now the only browser that can’t resize pixel based fonts. Is there anything else I’m missing? Would love to hear it! :)
Hi Mike
My first attempts at CSS were a real mess. Just randow rules one after the other.
Most of the time was spent looking for IE fixes, so if the page looked OK I was happy.
Then I realised that it was almost impossible to edit, and I started using comments and some of the other “housekeeping” that you show above.
Much easier to edit now.
I was interested in your comment “The file size is quite dramatically cut down”
With Google (Matt Cutts) warning about page download times, I might start looking at the “Minify CSS”
It’s a nice tool Keith. There are other more effective ways of cutting load times that you might want to look at first, but when you’re done with them and you want more, it makes sense to shave what you can from your CSS (and JS!) files too!
Sounds like we have essentially the same CSS habits :-)
I always section into header, content, footer and any other major sections, and I use single line, often indented. I hate looking at multi-line CSS, it’s such a waste of space and takes forever to find anything. Of course, I don’t mind if anyone else wants to use it, I just don’t want to.
I still like to use ems sometimes, especially when I don’t need something to be pixel perfect. If I just need a bit of extra space between some items 0.5 or 1em usually works well.
Sounds like we do Kristarella! We’re agreed on everything there :D
I like your example of when to use ems there too. That makes a lot of sense, definitely nothing wrong with using them that way! :)
After a decision to block IE6 users from now on, px is suddenly opened to me again. Very exciting!
Also some really interesting arguments for single-line CSS. Again, it’s something I’ll definitely reconsider now. Just finding the selector does seem more important than the selector’s individual properties. Good point that!
Great article, many thanks.
No problem Richard, let me know how you get on with trying out single line CSS!
I’m curious about your decision to block IE6 users. Are you blocking them fully, or just giving them a really stripped down site? Either way, definitely sounds like px is the way for you!
Yup – I’ve decided to block IE6 using ‘IE6 upgrade warning’
http://code.google.com/p/ie6-upgrade-warning/
I felt like I was just wasting too much time trying to make sites look in any way decent in IE6. The IE6 user will be presented with a screen (looks a bit like the notorious browser choice screen really!) where they can choose to upgrade IE or select another browser. I guess it is pretty aggressive and I’ll keep an eye the analytics to see just how many people I’m blocking, but I personally feel it’s time to get pro-active in stomping out IE6. Feels a little scary and very liberating!
I would show a little bit more understanding: often people have no choice, such as many UK government departments only providing IE6 on employees’ computers for example. That’s a lot of people stuck with it.
Yes, IE6 is annoying, but it’s not that difficult to design for – just accept that your sites might not look quite so perfect. Blocking users is really not a good attitude to adopt.
I totally agree with your comment about the interesting arguments for single-line CSS.
I think I’ll also start writing single-line CSS from now.
Nice tips, although not new… it helps to revise the techniques…
Thanks for sharing..
Nice post, I still using multilines, it´s simple to understand what others writes in the code.
Great work on the post, thanks…
Back to the basics. Always good to remind you to “keep it simple”.
I just switched from px to em but seems that i’ll have to take a good look again and decide wich one i’ll use.
Love this part “Don’t Worry About Ems”
I thought I was alone. Building extremely complex sites for the company I work for ems are just a pain in the arrss
Michael, thanks for the tips certainly food for thought. Will give them a try. I hope you don’t mind that I copy and past this post into word for reference?
Regards
I would argue to always use multi-line CSS especially if you have 4 or more styles on a selector. It will make you faster in seeing what is going on and other designers/coders won’t beat you over the head if they are trying to edit your code.
Another tip I would recommend is to indent child selectors so you can see relationships easier.
I only use multiline when I use -moz -webkit selectors. Imagine having this on one line
-moz-border-radius:100em;
-webkit-border-radius: 100em;
border-radius: 100em;
width:92%;
height:92%;
margin: 8% 0 0 0;
float:left;
I think that when css3 is well supported one line css will be obsolete
Great post, I use to write multi line css but have moved towards single line css and I am getting better with the short hand. For me it seams to make it faster to read and write single line css.
I prefer to keep the same elements on the same line, but break them up by elements. I also then organize it by property, so a typical css style would look like this:
#wrap {
background: #fff url(../images/bg.gif) top center no-repeat;
width: 780px; min-height: 437px; height: auto !important; height: 437px;
overflow: hidden;
clear: both;
}
Sorry, hit the reply button too fast. The entire css property would be like:
#wrap {
background: #fff url(../images/bg.gif) top center no-repeat;
font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #777; font-weight: bold;
width: 780px; min-height: 437px; height: auto !important; height: 437px;
padding: 20px 20px 0;
margin: 0 auto;
overflow: hidden;
clear: both;
}
That’s pretty cool Zach, I like the idea! Seems like a nice middle ground between the 2.
Ems are a pain, but I moved to percentages, and I haven’t really had any problems since. I suppose pixels are easier, but I still have 10%+ of users of my websites using IE6. So percentages it is.
thnks for share…
Great tips, I did a similar post recently and got ripped apart for suggesting that single line CSS was easier to read. It certainly is for me, I hate reading multi-line CSS. Not only that, with single line I don’t often have to do any scrolling, I can see the whole site’s CSS on my monitor. Can’t do that with multi-line.
I suppose if you train your eye it can be easier to read, but for me it is not. I have edited other people’s one liner CSS and there was so much going on that it just looked like a wall of text. Certainly not easy to read.
If I have things organized out into sections, and multi-lined then I can easily see what is going on.
Agreed on that one Amber! I prefer single-line CSS by miles, but I know the people who prefer multi-line CSS really hate it. It’s strange how so many people can swear by one way or the other!
I actually read that post of yours a few days back, someone mentioned it higher up in a comment on this post. Seems like we have similar coding habits! :)
Like @rilwis, i also alphabetize properties – when i first heard about it i thought it was just over-the-top nerdiness, but i tried it and have never looked back. it just makes it so much easier when reading through your file, and it’s now second nature to me when writing new css.
and yes i admit it, it also satisfies the nerdy obessive in me :-)
Single-line rules are the way to go when you’re working on a CSS-heavy site. This allows you to read multi-rule patterns more easily and navigate hundreds of rules more efficiently.
Multiple selectors are definitely underused. With IE6 ( 20% share according to some) you have to keep in mind that the following CSS will make ALL of your .alignLeft links blue ( in IE6):
.alignLeft { float:left;}
.header.alignLeft { color:blue;}
Hi folks, nice post! :-)
I’d advice you NOT to use the CSS Reset with “*” selector. Bad thing about this is that some form elements get broken (radios, checkboxes, buttons, submits) and you’ll hardly repair them so that they look well in all browsers and platforms.
A good solution is to write out all elements you need to reset:
div, p, ul, ol, li, h1, h2, h3 {padding: 0; margin: 0;}
I would like to advice to keep a non-minified copy of your CSS somewhere on your HDD, because once you minify it and everything is clutched together single lined, without comments, it’s a little bit hard to read and edit :)
Also it’s not a bad idea to have a separate CSS for IE6.
Nice article Michael!
Now, I’m sure you have foreseen getting quite a few comments on “Don’t Worry About Ems”, and this is another.
I’m curious as to where you got your source for “IE6 is the only browser that still doesn’t scale pixel sizes”.
According to the article below, and my knowledge up until this point, all versions of IE have the same problem with scaling pixel fonts:
http://www.kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/
Great post! I think that making everything single line may cause a bit of trouble if you ever need to make changes in the future, but saving a development copy and then using a minified version for production is a great tip.
Sectioning your code is a great tip as well. I like to keep a bunch of generic class styles handy as well for things like floats, italic/bold, underlines, etc.
Great CSS tutorial. And thanks for sharing link to CSS Frameworks. They are really handy :).
I do as well write my css one line. Still, I try to keep some order.
Core properties first then other.
I mean by that : position, float, display, width & height will with me always come before background, font and colors.
Never tested but I believe the rendering engine works better that way. (sounds kinda logical to me : where then how)
I like as well to put quite some comments for maintenance purposes. (Either for myself or others)
As for ems/%/px : I use px, so much easier. IE6 ? Sure taken into account, just fonts wont resize ! Can’t go 100mph with a 100years old car can you ? Same here : Don’t expect latest tech with outdated tool. :)
btw : I use same tech fot header positioning. Elegant & efficient !
I have two css files. One is a skeleton of the web – template.css – and contains height, width, margin, padding, position, float … etc. .. of body, header, left, page, right, footer. In the second file – page.css – are defined background color, font size and all elements contained in block #page. So the Web is easy to repaint.
All of above! Well, I use % for font size though. Maybe pixel works much much easier :)
This has really help me. I have used some of the tips in here. Thanks. It is really great to stay on this blog.
Pixels? Well .. lets see: Set 10px to body, right? If created on a windoze system with high screen resolution and low DPI – automatically looks horrible on Mac + Linux, ie. unreadable.
So indeed, pixels are the worst idea you can come up with. Better try points or percent.
BTW: For proper and safe URLs, add quotation marks. Like this:
background: url(“../../images/bg/01.jpg”) 0 0 no-repeat;
And that idiotic idea about putting everything in one line … sorry, but its very UN-accessible and UN-readable. Especially if you give this piece to someone else to work with. And just for your enjoyment, because YOU work better that way? Sorry, but we all have to make compromises. Including proper coding rules – just take a look at the PHPish mess that happens w/o any proper standards with most themes for WordPress.
Let’s just say: Spaghetti code.
cu, w0lf.
That tone isn’t constructive or helpful.
The article states that it’s his preference to use one-line but that it’s not for everyone… way to knock down a straw man.
As for the px, you don’t quite understand how browsers render, do you? It has nothing to do with “DPI” etc. And the way browsers render, the “em” unit isn’t a DPI thing (a ridiculous concept, once again…) but rather a percentage thing. The formerly-espoused “best practice” was to set an even baseline font size… in pixels… and then use ems to scale up or down from there, which ends up working exactly the same as using %.
In other words, at the end of the day, they all end up equalling an instruction like “render at this size”, which will NOT affect another browser rendering it as unreadable. A font defined as 10px will look the same as a font whose baseline is 10px/0.625ems and is styled to be 1em, which will be the same as a font whose baseline is 10px and is styled to be 100%. They will all render identically regardless of the arbitrary unit of measurement chosen. The choice of unit doesn’t force the browser to magically render like garbage…..!!
Hi fwolf,
About the single-line code; I know that it’s not for everyone; the same way multi-line isn’t for everyone either. Having to edit a huge multi-line file annoys me just as much as I imagine a multi-line coder having to edit my file would annoy them! It’s difficult to say what the best solution would be, but forcing either side to go one way isn’t compromising, that’s just saying to use one side
(And perhaps that really is the best way to do it in a team. It will annoy a few people, sure, but the consistency is vital for the team as a whole).
About the pixel fonts, Greg replied to that far more elegantly than I could have! Thanks for taking the time to respond here Greg! :)
I pretty much write my CSS as you appear to do, with a couple of exceptions.
Firstly I still use em’s, by setting the body font size to 62.5% you have a base size of 10px so then em’s become pretty managable. I also don’t minify my CSS other than in some circumstances. I tend to find it’s annoying to have to unminify CSS to then edit it, plus with server compression like gzip it shouldn’t be necessary.
When writing single line CSS one thing I find that makes it all still easily readable is for your attributes to be ordered alphabetically so your css might look like this: {background; color, font; margin,width}
Muito legal o seu post! Eu sigo todas essas dicas nos meus arquivos de CSS.
Parabéns.
Thank you for sharing your knowledge … was very helpful!
I’m definitely a single line coder, when I first started I used multi-lines but sometimes this would cause me to have really long stylesheets and made it very hard to find things. Single line is definitely my preferred option now, not only is is easier to find things, but it is quicker to type and load.
Also only up until recently have I massively improved on my shorthand CSS techniques. For instance using margin-top:0; margin-right:10px; instead of margin:0 10px; etc. Im still not perfect when it comes to shorthand though, its not an easy thing to get of the habit.
Each to there own though, I think there will forever be a debate on single line or multi line.
I always like to hear how others do their CSS. Thanks for sharing.
I’ve recently started single line because it’s so much easier. Maybe my projects are getting more complex, or maybe it just seems easier now. Certainly it saves a few keystrokes.
I liked the details on header layout, much easier.
Good info!
Great article. I definitely have a preference now with single line css, much easier to read. I never knew about combining classes, great advice. Thanks again.
I keep coming up against the issue of where to put a selector in a style sheet for a large, complex site. I typically start out with sections for Structure, Links, Typography, Colors, Forms, and such. But then when the various pages’ content starts getting generated dynamically and you have to go back and start writing various more specific classes for things, such as the color of h3s in a particular div, then I wonder, do I keep those with all the typography or the color, or do the exceptions get added to their appropriate Structure “section”, say, Header, Footer, Maincontent, etc?
I always start out with good intentions but the css file just ends up becoming kind of a mess as more things arise and have to be addressed piecemeal.
Nice reminder post. And, BTW, really diggin this blog design. :)
Coding Css on a single line is easier to read for me, however I use multiline too and my stylesheet is a hybrid.
Never thought to position absolute the header elements.
I agree with all point all are good suggestion. except one
Em would be good for IE6 and as well as for mobile browser also I think. These days many people use internet on mobile.
That’s true, but with touch phones at least, it’s all zooming as well so pixels are fine there.
I confess I’m not familiar enough with Blackberries and other non-touch phones to know how they resize their fonts though. A lot of mobiles use Opera Mini though, and Opera’s main browser at least hasn’t had issues with ems in years, so maybe that’s carried over to the mobile browser as well! (or maybe I’m just getting hopeful! ;) )
I agree on almost all your puoits but 2:
– EMs are not used only to bypass an IE bug, but to make the text size based on user preferences. This is becoming more and more important with portable devices. Using font-size:62.5% and then sizing fonts in em lets the user choose his preferred font-size at browser config level, avoiding the need to zoom to make in readable on “not-1280×1024” screens.
Of course not everything must be em sized, but it is also useful with min-width and max-width to limit the text column to some sane size, or to define a line-height based on font size.
– I think multi-line editing is better. You can use a little-better-than-basic text editor to gain text folding. You can fold the whole css, and unfold only the element you are editing. This way you get the best of both worlds.
Bye.
Nice tip on the text editor Alex. I’ve never tried that (because I use single-line), mind sharing what text editor you use for it though? I’d be curious to try it out!
I am using single line. Not that readable though but I really likes how these selectors lines are displayed on the page.
Very nice article, I didn’t know that you could assign multiple classes to a single element! I always ended up using additional divs and spans or creating specially combined selectors.
Thanks!
Like many of your other 60+ comments I agree this is a great tutorial and has some great suggestions to make things easier should a site get passed to a new developer/company for maintaining and updating. I do sometimes find it frustrating the different methods that people use to accomplish the same end result.
Glad I found your site through someone’s blogroll (though now I don’t recall who’s that was).
@ProjectCenter
Nice the article, thank you
In the passage I wanted to share a video that we realized during the last lounge(show) on the graphics(handwritting) and our jobs(businesses):
http://www.youtube.com/watch?v=cL1Msk4I_m0&feature=player_embedded
Thanks very much for this extremely informative article.
I didn’t know that you could assign multiple classes to a single element! I always ended up using additional divs and spans or creating specially combined selectors.
Great…Thank you…
I just learned html/css coding…and after visiting this blog i got this post very help in increasing my knowledge.
So true… I have to admit my css files are a total mess sometimes… except from filesize that won’t be any problem… as long as I’m the only one who has to edit them ;-)
These sorts of “best practices” blog posts seem to be cropping up again these days. Its worth having a new batch every few months.
I’m always surprised by what is missed.
First best practice for CSS really should be “Learn how to calculate specificity” followed by “Use specificity to make your selector as specific as necessary”. By far the most valuable part of CSS is the specificity and how selectors are applied… and few people use it well.
Also I get wierded out by “use shortcuts” which is mostly “use shortcuts for background”, after all, when was the last time you wrote border-right-style (border-right, to be sure but that’s a shortcut in itself). The problem with the background and font shortcuts is that its VERY easy to set too many things. Even though it works to use “background: red;” you may unintentionally reset the background image and the rest to their defaults. This is particularly true if you’re using multiple class names.
I think shortcuts are a case of premature optimization. When you’re developing your CSS, use NO shortcuts. Then after your first pass, see where you can and should introduce additional class names (or additional selectors), into which you can move some of those styles. Once you’ve done all that, recombine the shortcuts that are left ONLY if the selector already uses all parts of the shortcut.
Speaking of multiple class names, “left” is a bad choice. You’re introducing style back into your content. It more efficient, but just as evil as using font tags. This is particularly true if you’re creating style for content that you expect someone else to manage (notably a someone else who isn’t HTML aware).
Lets say that you have a product page and you plan to allow images in the copy. You’ll have a standard photo of the product itself and some collection of customer action shots. The product photo will float left and the action photos will float right, except for the most interesting which will be floated left.
The temptation is to assign a .left or .right class to the images (or the relevant element that contains them) but that temptation should be resisted at all costs. What happens next month when you decide to redesign the site and now the image positions will be reversed. Now you have to either rewrite all your content (potentially a lot of manual work) or have the unpleasantly confusing situation where the properties in the rule are dissociated from the implied meaning of the selector. Imagine:
.floatLeft {float:right;}
Or imagine the horror of designing a nifty little callout where the text is made 3em, and floated right. You might add “big” to the “right” classname you already have. your content author is going to start putting the “bit” class name on random stuff because they really think it should be big.
The better solution is to use class names that are intention revealing. In the above cases (lets assume the image is wrapped in a div so that you can also have a caption) you would want to have a generic class called “media” or “image” to handle things like styling the caption and attribution, “primary” or “product” and “secondary” or “action” to distinguish between the types of photos and “important” (or something similar… I’m bad at picking meaningful names) for those secondary/action photos you want floated right. Similarly the call out above should have a “callout” class for the styling and perhaps “primary” and “secondary” for handling different types of callout.
I have to agree with cleaning after your CSS file. When you’re working with CSS and you start adding different codes, its easy to forget to take them out if you decide not to use that style later. Like adding style to tables and later scraping tables within your html part completely. It’s a good practice to read over the entire thing once you are finishing up your project.
This was a great read. I’ve been teetering between a few things: multi-line/single-line, ems/px, header layout… but you’ve made up my mind on these things. Thanks! My life should be much easier now. :)
Very cool article (and some good comments too!). I stumbled across this site from someones post on the wordpress forums. And…..now I’ve gotta scan through my css on my WP theme, I think I got some cleaning/fixin/sortin to do.
i wish you have written this article sooner! most of the things I have to find out myself :(
point 1: multi-line is great for updating/fixing web site but for developing
it’s a waste of time (too much scrolling)
a main point: Start With a Reset
well, this text which should be written in the rock
I’m a huge fan of Type Pilot Software it makes managing a CSS file much easier.
Good stuff. I totally agree about the pixel v em/percentage business. There are a handful of these (obsolete) accessibility requirements which really belong with browser developers rather than website builders…
Here is something that I like to do that most designers do not:
div#foo
{
height:100px;
width:100px;
}
Some say it is a waste of line space to put the opening curly bracket on the next line after the selector but for me it helps break up a long css file. I use css compression in all my projects anyways so I am not concerned about line spaces when it come to performance. What do you all think?
I used to do that when programming and have started getting back into it… I agree that whitespace is a good thing, esp when you have css compression.
Incidently the style…
code {
code
}
…dates from when compilers were less sophisticated. The curly brace needed to be on the same line to indicate that the code that follows is related. Or so I’ve read!
These really helped me to build my homepage, I can really appreciated if people take some time and write a usefull tutorial.
I think this is better (without extra space and it looks beautiful):
.title {
font-size: 14px;
line-height: 20px;
color: blue;
}
Good stuff. I totally agree about the
Until a few months ago, my CSS was a mess, there was no logical ordering or seperation between differant parts and any new rules just got stuck on the end.
I also used multi lines CSS, seperate rules and so on.
Now, I do pretty much everything you listed in this article, and it makes it a *lot* easier to work with!
I think the biggest improvement for me though was going from multi line to single line. It’s much easier to scan through it, and in most cases, you’ll only have a couple of things for each rules, so you can see it all at once without horizontal scrolling, so it’s not really an issue
I would encourage everyone to use a CSS editor/validator to ensure that they develop correct CSS.
Great read Michael and I adhere to many of the same practices. I use Firefox’s Web Developer’s toolbar to validate my CSS and HTML.
I place related rules in sections with clear headings in uppercase for quick reference:
/* LISTS
——————————————————————————————–*/
I write my rules as follows:
h1
{background: url(/img/markers/down-arrow.gif) no-repeat 0% 50%;
border-bottom: 1px solid #005CA1;
color: #005CA1;
font: normal 1.4em georgia, garamond, times, serif;
margin: 3px 0 15px 0;
padding: 0 0 0 12px;}
I separate my rules into different CSS files such as screen, nav, form, print, and reset. I find this to be a more efficient method because I don’t have one huge file to manage and modify. If I have a form element to change I simply open my form.css file.
In addition, I list them all in an import.css file, and my reset.css file is listed first:
I’m also very cognizant of specificity, which helps address inheritance problems:
body#products div#rightcolumn ul li ul li
{list-style: circle;}
Again, this is what works for me.
-MC
Great read, nice to see how other people code, I tend to write my CSS pretty much in the same way as you!
Thanks for sharing.
I tend to write my CSS pretty much in the same way as you!
I think the biggest improvement for me though was going from multi line to single line. It’s much easier to scan through it, and in most cases, you’ll only have a couple of things for each rules, so you can see it all at once without horizontal scrolling, so it’s not really an issue
These really helped me to build my homepage,
didn’t write CSS yet, try it soon.
Read many articles here, so many useful information for wp , thanks.
Very good set of tips.
START WITH A RESET is vital for me, building websites for different browesrs can be a nightmare, the RESET gets rid of all that messing around. And USING COMMENTS helps you when you come back to old websites.
$latex GOOD-MORNING
&fg=333300&s=4$
$latex GOOD-MORNING
&fg=FF0000&s=4$
Thank you for these tips! I’m just starting out myself and a lot of this stuff is coming in handy. Much appreciated. :)
Thanks for sharing, I always studying css to design websites.
Great article and always interesting to see how other people write their CSS. I write my CSS almost the same way you do and some good tips here. Thanks.
Want to be emailed when new comments are added?
Using classes is simple. You just need to add an extension to the typical CSS code and make sure you specify this extension in your HTML. Let’s try this with an example of making two paragraphs that behave differently. First, we begin with the CSS code, note the red text.
Thanks for the great post. Now get back to work applying tips from this post. I will use at list four on my websites: single line, shorthand css, multiple classes on one element, sectioning.
Every browser applies its own slightly different styles to elements by default.
Thanks for the great post.
If you use Firebug Firefox plugin it creates shorthand CSS which can be copied and pasted into the live css file when you’re happy to commit the code. I couldn’t be without it.
I found this blog really helpful! Having developed my first commercial website just recently I have realised just how important it is to take the time to structure CSS so it’s easily accessible for myself and my colleagues. Also I have found that I am coding my CSS on one line which is great because it prevents having to scroll through what appears to be masses of code.
Great post thanks!
I think I will have to disagree with the positioning one, I don’t know why I just have a thing with positioning, I used to use it all the time when I first started but now I use margins and padding all the time.
Just my personal opinion ^^
Interesting post. I have been wondering about this issue,so thanks for posting.
These facts are amazing .
I was searching before last 5 weaks and ia dint get the perfect answer.
But after all i found from your site.
thanks for posting such a interesting topic.
An invaluable resource and great addition to my favorites. The new features are well received on this end and will surely help the community share and progress more rapidly.
Cleaner Services Sydney
something that’s eye opening and important.
What’s really interesting, though, is that not all of those SEO blogs
on the list have nofollow implemented on their comments.
Really i am impressed from this post….the person who create this post he is a great human..
For me the Informations are really really useful for my research. I’ve Bookmarked this page for future reference.
I like to use single-line rules in my stylesheets. It is shorter and easier than other. I liked this post and i think that can helpful for beginners.
thanx
Now that you (we) got quite some comments on this thread…. How about checking them and seeing what & how people do it ?
Good to show what you think (blog article), good to ask what people think ( article discussion), good as well (the yet missing one) to close coments and have an article summarizing comments.
What do you think ?
I remember reading this post a while ago and it made me start to think about what type of developer I am when it comes to styling css… after quite a bit of practice now I have realised that I’m a one line css coder, I always use basic shorthand everywhere but fail to remember the order of shorthand for font styles etc. As for the comments and white space I love it but maybe should make a separate style sheet like you suggested for the robots and keep my “user friendly” on for myself.
It’s really
helpful for
me which I
have ever seen.Its
presented well and nicely written
which easy to understand.Thank you very much for the information.
I would like to thank you for the efforts you have made in writing this article.
I am hoping the same best work from you in the future as well.
Great post. Very useful for everyone. Thanks for sharing such a nice post and points. These point will really help me
Great article and always interesting to see how other people write their CSS. If you use Firebug Firefox plugin it creates shorthand CSS which can be copied and pasted into the live css file when you’re happy to commit the code. I couldn’t be without it. I write my CSS almost the same way you do and some good tips here. Thanks.
Well, as I am using most of the techniques you’ve been talking about, I cannot say I do not agree. In fact, they are really effective. But when I code a template that goes public (available for download) I use multiple lines and a lot of comments, so that every start-up can get a clear understanding. Thank you!
Great CSS tutorial. And thanks for sharing link to CSS Frameworks. They are really handy :)
Great tips! thanks for sharing this code. It really helps to construct designs.
I appreciate the work that your are doing,
If you are having trouble editing someone elses CSS code the best solution that i can provide is to use a firefox browser and download fire bug for your firefox and that allows you to see what CSS directly effects each element of HTML on the page. Its a great wee tool and worth a look if you have never heard of or tried it
I usually do go through the spam filter, so even the simple fact you have a Gravatar
I am using most of the techniques you’ve been talking about, I cannot say I do not agree
Really great tips!
Really nice tips out there….
The shorthand CSS bit is something I will definitely try to make a habit of in coming css files. Thanks for the post!
Interesting comment on using px instead of em due to the way modern browsers work – will look out for other people’s blog posts on the this subject to see if this is the way things are going.
As for single line vs multi-line – for low traffic sites, we do multi-line for legibility but for high traffic sites where every KB counts, a single line, minified CSS file makes sense.
Nice refresher. I really need this kind of stuff since I am planing to create new site using CSS.
Yep, CSS seems to be a great technology when designing websites!
This is a nice refresher. I really need this kind of stuff since I am planing to create new site using CSS.
Thanks for the tips. I will definitely use this Shorthand CSS.
you can use in your CSS to make your stylesheets easier for you to read, and easier for
gotta love multi line CSS!!
Website Facility – Milton Keynes
I prefer writing in multi-lines, after finishing they will be compressed and than gzipped!
The clarity in your post is simply spectacular and i can assume you are an expert on this field. Well with your permission allow me to grab your rss feed to keep up to date with incoming post.
Thank you for your advice. I will use this to edit our CSS in webdesign.
CSS is still a struggle for me, but this has helped.
I enjoy your weblog and will sign up to your feed so I will not miss anything. Fantastic content.
This wil help me with the redesign of my site.
I currently use multi-line css and it works for me so….
I do make extensive use of comments, plus divide up the style sheet into ‘sections’ such as:
/* mini mass reset */
/* boilerplate elements */
/* standard htm tag elements */
/* left nav elements */
/* default link elements */
/* footer elements */
etc etc etc just to help me find my way around.
Something else to mention, as my site has sections within it that require very different content items, I tend to use separate mini style sheets for each of those sections’ unique elements. They are then linked to the xhtml page just as an additional css link. This keeps the site wide css file smaller. This might seem excessive, but again is a system that works well for me.
And…. pixels all the way :)
Cheers
I
The date is almost upon us; WordPress 2.5 (remember, 2.4 was skipped) is almost ready to make its official debut come March 10, 2008. The release date has been pushed back, but it should be released by the end of March, 2008.
http://commodityconsultant.com
Right now, it’s still quite rough and is currently undergoing some final rounds of testing and tweaking; but it’s solidified enough to give you a quick overview of some of the feature changes and additions, along with how they compare to the WordPress 2.3.x branch. Prepare yourself for a change.
Great tut! I have to say one of the most annoying things is having to go back behind someone to fix a problem, and find that their code is NOT documented cleanly. It really does make a difference. Thanks for the reminder!
.example {background: blue url(images/blue-bg.jpg) 100% 0 no-repeat;}
to :
.example {background: blue url(images/blue-bg.jpg) no-repeat;}
This was a very helpful article. I will be referring back to this in the future! Thanks for sharing.
This was exactly what i was searching for. Have been fighting for a while to do this, thanks for have posted.
Intimately, the publish is truly the top on this valuable subject. I concur with your conclusions and will eagerly look forward for your coming updates!…
This was a very helpful article.Have been fighting for a while to do this, thanks for have posted.
I always wanted to learn how to use CSS, this article will help me do that.
This list of practices about CSS is great. I will use this in designing websites.
This practices are very good. Less code more design.
The idea of a reset is to take away all of the styles a tenant Screening browser might add. It helps a great deal when it comes to browser inconsistencies.
Excellent guidance and really enjoyed by reading this post.
Thank you. I’ll keep it as a guideline. I just started with this.
By spreading the different CSS properties out onto tenant Screening different lines, you make them easier to read. That’s a great help when you’re still getting used to CSS.
Hi
Great post. I am sure that I can improve my CSS if I follow these advice.
Thanks for sharing.
I have to say one of the most annoying things is having to go back behind someone to fix a problem, and find that their code is NOT tenant Screening documented cleanly. It really does make a difference. Thanks for the reminder!
Great post. I didn’t know about multiple classes for one element. It will realy help me. Thanks.
I prefer multiline to singe line. It is easier to maintain for developer. But when in deployment, we should minify the CSS to become single line to make the size smaller.
I agree when i first started with css i also spread out the css over multiple lines, then i started using the 1 line as it gives more structure. I also had a lot of help from the clear and reset options. Thanks for sharing!
Wow! Excellent collection of different designs. Thanks for sharing all of them!
Thanks for sharing the great post!
Nice post. When I first got into the coding scene, admittedly, I used to use the multi-line tactic with ‘s everywhere to get the desired effect and didn’t even bother to check to see whether it was cross browser compatible.
Since working within a web design agency though, I find myself using the single-line method ( I find it easier, faster and it consumes less space ) as well as designing to a certain standard that helps reduce the amount of CSS used. For example:- All my H1, H2, H3’s etc are the same, images have the same styling applied, ul’s and li’s are the same…you get the idea.
With these all styled up at the beginning, I find it easier to adjust the code if needed and save on adding extra CSS for each individual item.
yes ofcourse, practicing our own CSS to our style makes easy to read and easy to modifying them in the future, thanks for your ideas.
Hi, Great CSS tutorial about css, thanks for sharing link to CSS Frameworks.
Hi Martin,
I have been learning a lot about CSS, I too divided all section in different. but I love breaking up the css in different files which also makes it easier but it is not good for page load time.
However I have been use reset the margin and padding to in the body some thing IE give me a very heard time. I am using IE 9 beta, Still my site is facing problem with the cufon scripts still I unable to find the solution to it.
Anyway it was an awesome post.
-Imran
rheumatic pains, joint pains preventing the movement, and meniscal calcification of the knee, Arthritis and highest level of ethics has a role of similar cases.
I have bookmarked this page thanks for sharing it..
Good explanation about Basics in css , ;-)
As previous commentator said that it is a good explanation about css basics hope it will be helpful to every one…
Hi,
I think that the Multi-line approach is convenient whenever you have to edit a CSS that you didn’t write. The single-line approach is better size-wise but it may turn out to be a mess.
Excellent guidance and really enjoyed by reading this post.
I have written css with the help of your post, really it helps me a lot thanks for sharing it…
Very nicely written post it contains useful information for me. I am happy to find your distinguished way of writing the post.
Great post, Interesting layout on your blog. I really enjoyed reading it and also I will be back to read more in the future.
Some great solutions here. Thanks a lot for posting this
can you please explain me more about ems?
ems come els and before ens ;)
Great information thanks for sharing it, would like to have an regular visit…
wonder & great . I really thankful to you
The article is good I like this post!
“best practices”?
You’re encouraging people to write single-line, shorthanded CSS. This is the worst type of CSS for another developer to come into and try fathom. Multi-line without shorthand is by FAR the most friendly for a 3rd party developer.
Maybe you should consider other people who will be editing your CSS before you are so selfish when writing it.
Minify takes away almost all the benefit of single line CSS, and the short-hand doesn’t provide much difference once minified either.
My advice, ignore the paragraphs about multi-line and short-hand. Addiitonally the comments about EMs, IE6 is still alive (unfortunately), ignoring it is just lazy, there is no other excuse for it keep using EMs till IE6 is put to bed once and for all.
Thanks, needed some help with my CSS styles.
Great tutorial – very well written and with great result.
Nice the article, thank you
really very informative post for all the site owners
Great, Thanks for sharing this interesting and informative post.
Write Better CSS With Best Practices is helpful for us.Advantageously, the article is really the best on this notable topic. I harmonize with your conclusions and will thirstily look forward to your approaching updateshouston dentist
I am just learning to optimize the css files
Nice CSS tutorial. God knows I need all the help I can get with this stuff!
I prefer the one line method when I write my css. I only use a Style Sheet for all my styles within my web design, which is best practice.
A slewing bearing, also known as a slewing ring is often in large size, and mainly used in winder power generator and machinery like hoisting machines.
this post impressive me and i like it so very much keep it up
I try to learn something new on different blogs regularly. It is always refreshing to read posts of other blogger and learn something from them. penny stock brokers
Everyone has a slightly different approach to CSS. That’s part of the reason it can be a nightmare to edit someone else’s code. But there are a few good practices you can use in your CSS to make your stylesheets easier for you to read, and easier for anyone else that ends up modifying them in the future.
This is my first visit in this blog, and I’m impressed a lot. Before this – I’ve visited many blogs, but didn’t get quality information from them. But this blog is different; I’ve got some unique information from this. It’s really impressive. I want to thanks to the webmaster of this blog.
Good tips for people starting out with CSS. The days of using tables are gone and it is good practice to use css to style your entire website.
I.m just starting to study CSS. Thanks for sharing this. Very helpful for us.
I have this plan to enroll php and css class and this is really a helpful start. I know it would be another long and arduous process for me but at least I have to start at a relatively solid ground.
please more posts about this minify.css thing…
This is an interesting article with a lot of good information i can implement.
Why are we struggling to learn CSS?
Why not use CSS Grid Systems! Like:
– Golden Grid CSS;
– 960 Grid System;
– 1 KB Grid;
– Tripoli Framework
nad many more.
And what benefits have of Implementing a Grid System
•Gives your design consistency
•Allows flexibility between elements
•Can make your designs more usable and legible
•Reduces CSS coding errors
•For the most part, it eliminates the need for nested HTML tables
•Can be used sort of like a wireframe allowing you to plan
•“Blesses” you with cross-browser support
•Streamlines your development process for future projects
•Acts as an adhesive and encourages the correlation between separate page elements
•Makes it easier to embed images, text, and other visual aesthtics
I am here through Google search engine. I have read this post. Now my knowledge has been increase about above topic. Thanks to blog owner.
Wonderful place to stay. Great service and hospitality. We loved the breakfast. Will recommend to others and come again ourselves.
Thanks so much for sharing this!
Wow what a collection. I liked all the photos but loved the first one.
I feel using multilines is easier to understand, though the other way may be better. Thanks for sharing the tips.
I use a lot of the techniques above so that’s good as my style sheets are clearly as small as possible which helps! The only thing I was a little unsure of is compressing my style sheets using the resources mentioned. If you work on multiple websites then surely you need to be able to clearly see where things are quickly using your css comments etc that you would put into your site and yet that resource removes it. That makes it a lot more time consuming and surely cannot make that much difference to your style sheet. Source formatting your code should be more than enough.
I always wanted to learn how to use CSS, i love this trick
for me I prefer multiple lines when it comes to CSS3 like
-moz-border-radius and others, reason is you need to add other browser compatibility code, so editing the code is easy ;)
You Share Really good article. One extra point. Always make you article, page, or post super interesting to read. Make people want to come back for more.
I like what you guys are up also. Such clever work and reporting! It is indeed a good and useful one. Keep up the superb works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my website . I am glad that you just shared with us useful information. Please let us notice. Thanks for sharing.
Yes Michael, you have given nice tips and I like this post very much. CSS is very important for designing a website because you can easily maintain the website and also SEO point of view it is good and the reason is that it reduces the loading time. Hence it is good to practice the CSS rather than using table based design.
Hi,
thx for this nice Post. I also use the One Line Technique for my CSS. It Saves 50% of CSS Code for my Site. For Javascripts it is also possible to use a Cruncher to reduce the Size.
Best Regards Thorsten