Digital UK Design Blog

10 CSS shorthand techniques you'll use everyday

CSS shortland is a technique of writing mulitple declarations and values in a single line of CSS code. The advantages of using shorthand is to primarily reduce the CSS file size, but there are other benefits. A bloated and disorganised stylesheet can be hard to debug if you encounter problems, especially if you wrote it and another unfortunate colleage has to fix it while your away sunning it in some hot climate.

To make it easy we’ll look at the most commonly used CSS declarations, write them in longhand, then sprinkle our magic, resulting in a neat, short line of code.

There are many permutations you can use with each declaration and using them all in an example would be a headache, so we’ll pick one, then simplify that, hopefully giving you a flavor of CSS shorthand.

0 values

The golden rule is if the value is 0 you don’t have to specify the unit (px/em/%). You may write:

01|  padding: 10px 5px 0px 0px;

try

01|  padding: 10px 5px 0 0;

Remove Selectors

A selector is basically the element you’re applying the styling to, for instance h1, h2, h2, div, strong, pre, ul, ol etc.. If your using a class (.classname) or an ID (#idname) you don’t need to include the selector within your declaration.

01|  div#logowrap

let’s lose the selector from within this CSS declaration

01|  #logowrap

So the selector in this case was div

* is the joker in the pack

Use * wisely in CSS as it’s a firey little monkey. * is a wildcard declaration, you can use it to set a group of declarations to all or parts of your design, for example:

01|  * {
02|  margin: 0;
03|  }

This declaration would set the margin to zero on every element on your page. Alternatively, set this wildcard with an element, such as:

01|  #menu * {
02|  margin: 0;
03|  }

This declaration would set the margin to zero on every element within #menu.

Backgrounds

Background properties include the ability to set a colour, an image, image position and image repetition. You could write:

01|  background-image: url("logo.png");
02|  background-position: top center;
03|  background-repeat: no-repeat;

Becomes

01|  background: url(logo.png) no-repeat top center;

Colours

The most common way of specifying a colour in CSS is to use hexadecimal notation: a (#) followed by six digits. One great shortcut that many don’t know about is that when a colour consists of three pairs of hexadecimal digits, you can omit one digit from each pair:

#000000 becomes #000, #336699 becomes #369

This technique only works if you have three pairs, here are some examples where you can’t omit any values:

#010101, #223345, #FFF000

Margin

Apply margin to all four sides of an element like this:

01|  margin-top:0px;
02|  margin-right:10px;
03|  margin-bottom:0px;
04|  margin-left:10px;

Let’s simplify this even more by removing zero value prefixes and merging it into one declaration:

01|  margin:0 10px 0 10px;

When applying padding, margin and border (and possibly a few others) you set these four values in a clockwise direction. Compare this to the hours on a clock, start with 12, 3, 6, 9, all in a clockwise direction. With this in mind there is another trick to slim this declaration down. Look out for two pairs, if the top and bottom match, and the left and right match then your a winner! Omit the 3rd and 4th values. The first value represents the top and bottom value, the second represents the left and right.

So let’s simplify this declaration down again with the pairing technique that’s just been explained:

01|  margin:0 10px;

The result is the element would attain margin of 10px to the left and right sides, and zero to the top and bottom. Here are a few declarations where the pairing technique can’t be applied:

Padding

Same principles in padding as explained in margin above.

01|  padding-top:0px;
02|  padding-right:10px;
03|  padding-bottom:0px;
04|  padding-left:10px;

Becomes

01|  padding: 0 10px;

Borders

Borders are a bit more complicated since they can also have a style and a colour. To give an element a one pixel solid black border on all sides, you could write:

01| border-width:1px;
02| border-style:solid;
03| border-color:#000;

Becomes

01| border:1px solid #000;

I typically write in order of width style color.

We can also set different widths on all four sides of the box element by writing:

01| border-top-width:1px;
02| border-right-width:2px;
03| border-bottom-width:3px;
04| border-left-width:4px;

The CSS shorthand for this would be:

01| border-width:1px 2px 3px 4px;

Finally we could style just the left and right like this

01| border-right:1px solid #000;
02| border-bottom:1px solid #000;

This would be

01| border:1px solid #000;
02| border-width:0 1px 1px 0;

Set a default style for all four sides then overwrite the widths below.

Fonts

There are many properties for font, just like the background properties. In a complex string you may write:

01| font-style:italic;
02| font-variant:small-caps;
03| font-weight:bold;
04| font-size:1em;
05| line-height:150%;
06| font-family:Verdana, Arial, sans-serif;

You could write

01| font:italic small-caps bold 1em/150% Verdana, Arial, sans-serif;

Lists

01| list-style-type:square;
02| list-style-position:inside;
03| list-style-image:url(filename.gif);

And finally

01| list-style:square inside url(filename.gif);

Credit to 456bereastreet for the inspiration to write this useful 10 shorthand CSS tips.

If you want to download a quick reference guide in PDF you can by clicking this link.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • DZone
  • E-mail this story to a friend!
  • Facebook
  • FriendFeed
  • Identi.ca
  • LinkedIn
  • Mixx
  • MySpace
  • NewsVine
  • Propeller
  • RSS
  • Sphinn
  • Technorati
  • Twitter
  • Yahoo! Buzz

Related posts:

  1. The beginning of the garden
  2. Garden Shed
  3. Get 20% off at Istockphoto.com with this discount code - my choice for microstock
  4. CSS for ABSOLUTE BEGINNERS - shaping up with CSS
  5. CSS NEWS - A quick catchup

53 Responses so far

  1. rick Says:


    Wow, I’ve been using the border overloading one ever since I learned css, I’m so glad to see shortcuts and overloaded css functions so functional and easy to understand.

    Thanks for the great list!


  2. Kim Says:


    Hi,

    Thanks for this great lineup. I’m a little sceptical though about the “Remove the selector” item. In most cases you can, but there are examples where a selector is necessairy.

    Say you have the same class, which u want to use for 1. divs, and 2. paragraphs. You should apply the selector then, no?

    I think therefore, that it is better to always apply, then to generally leave out, and encounter conflicts.

    All and all still a great line up!


  3. frog Says:


    Hi Kim thanks for the comments.

    Selectors are a debatable subject in CSS, some deciding to use them and others deciding against. I think the golden rule here is to be consistent in you choice, either use them all the time or not at all.

    I personally don’t use them because sometimes I want the same class and styling on several different elements, using selectors in this case would cause me problems.

    Where you want to use the same class for 1. divs, and 2. paragraphs, you shouldn’t include the selector. Having div.classname would mean these styling declarations won’t apply to the paragraphs with that class name.

    I feel the only use of a selector in your CSS file is if you have no other choice but to use the same class name on different elements in your page, using the selector to distinguish between them in your CSS file.

    Hope that makes sense :)


  4. rmf Says:


    For the example:

    #header #menu * {
    margin: 0;
    }

    You say “This declaration would set the margin to zero on every element within #menu.”

    But I believe this is slightly erroneous - it would only set the margin to zero on elements of #menu if #menu is a descendant of #header.


  5. frog Says:


    Yes your right, this example does rely on #menu, in simple terms, being with an element with an ID of header.

    #menu * {
    margin: 0;
    }

    This would have been a simpler example but I think we’re on the same wavelength.

    I will correct the article so others won’t get confused, thanks again :)


  6. Drew Says:


    Hi there,

    Nice list, very well written. One thing though, and please correct me if I am mistaken but isnt this:
    #menu * {
    margin: 0;
    }
    A little redundant as the * could be omitted like below:
    #menu {
    margin:0;
    }

    Am I wrong here? Anyway, again, great list.

    Regards,

    Drew


  7. rascunho » Blog Archive » links for 2008-09-30 Says:


    [...] The Frog Blog » 10 CSS shorthand techniques you’ll use everyday (tags: http://www.thefloatingfrog.co.uk 2008 mes8 dia30 top10 shorthand CSS blog_post) [...]


  8. frog Says:


    Hi Drew

    If you had a DIV let’s say with the ID #menu;

    #menu {
    margin: 0;
    }

    Then JUST the DIV would have a margin of zero, now the following declaration instructs every type of element (p, ul, li, ol etc etc) WITHIN #menu to have a margin of zero, NOT the DIV itself

    #menu * {
    margin: 0;
    }

    So for example if within div#menu there was a P then that P would have a margin of zero.

    Hope that makes sense.


  9. Variolicious Says:


    [...] the css file smaller, of course, thus the downloading time will be smaller also. Other website from Frog Blog also teach how to use the CSS Shortcut as [...]


  10. Rob Says:


    Can I just say the design of your site is lovely. The colours you’ve used for the code snippets look fantastic, great work.

    Good tips to, admittedly I didn’t learn anything new, but keep up the good work nonetheless!


  11. frog Says:


    Thanks Rob appreciate the kind comments.

    I guess this article serves as a reminder to merely improve one’s CSS and/or maintain high standards.


  12. evertt de sousa Says:


    hi very good all this for sure will be a great help to me,
    I am very grateful to you


  13. squid Says:


    I read in one of the links you gave that an addition to your colours section could be that #A0B0C0 can be abbreviated to #ABC. I did not know this.

    Keeping stylesheets small is definitely worth the effort - especially in high traffic sites generating gigabytes of traffic every month for the CSS along.

    Keep your class and id names small, your syntax succint, and minimize it when you’re publishing it to remove superfluous whitespace (keeping the original of course!). CSS drive have a good compressor which I used on http://www.lrseries.com/ to good effect. http://www.cssdrive.com/index.php/main/csscompressor/


  14. frog Says:


    Dude, #A0B0C0 can’t be abbreviated to #ABC, who told you that? Or am I mistaken?


  15. squid Says:



  16. squid Says:


    Of course it’s nonsense … how would the renderer know whether you meant #AABBCC or #A0B0C0 … move along, nothing to see here.


  17. Gerhard Says:


    You can make the last border example even shorter :)

    your example:

    border:1px solid #000;
    border-width:0 1px 1px 0;

    because you will specify the width in the next line you can take it out on the 1st like this:

    border: solid #000;
    border-width:0 1px 1px 0;

    This works well and validates in jigsaw


  18. Robert Fauver Says:


    Never used the lists shorthand before. I’m glad that I read this.


  19. Andrew Challen Says:


    Be explicit about the background colour too.
    background: transparent url(logo.png) no-repeat top center;


  20. BobZ Says:


    background: url(logo.png) no-repeat top center; - very useful, but if the image it’s too big, the site will load too hard …


  21. Ben Wallis Says:


    You forgot border-color:

    border-color: #666 #333 #333 #666;


  22. frog Says:


    Hi Ben, you’ve taught me something there cheers


  23. squid Says:


    That’s a good one Ben.

    Are there any contractions where you can abbreviate the north, east, south, west values so that you didn’t have to specify all 4 if a couple of them were identical?


  24. Andy Ford Says:


    In the first example “0 Values” it says: “if the value is 0 you don’t have to specify the syntax (px/em/%)”
    The word ’syntax’ should be replaced with the word ‘unit’

    In the “Backgrounds” example, there is an opportunity to shorten the rule just a bit more:
    “background: url(logo.png) no-repeat top center;”
    can be written:
    “background: url(logo.png) no-repeat 0 50%;”
    (you just have to be careful to always put the vertical value before the horizontal value)


  25. Ethan’s Blog » Blog Archive » New Year (Jewish) Says:


    [...] Floral Brushes for Photoshop 35 Photoshop Tutorials Inspired by Apple 25 Ways to Spice Up Photos 10 CSS shorthand techniques you’ll use everyday Body Border 2: Fade In with Gradient BigTarget.js Animate a hover with jQuery Test your Website: A [...]


  26. saurabharya Says:


    very helpfil comment thanks for this i am really gonna use it..


  27. frog Says:


    @squid

    North East South west can be abbreviated to North/South East/west if the pairings match:

    margin:10px 20px 10px 20px; becomes margin:10px 20px;

    I’d treat this as the simplest Declaration there is


  28. frog Says:


    @Andy Ford

    Thanks Andy, you’re entirely correct.


  29. Elf M. Sternberg Says:


    I have to disagree with your colours recommendation. Consistent styling isn’t just something for the end product: future maintainers will have to be able to read your CSS someday, and having multiple (and for maintainers, sometimes confusing) ways of expressing the same thing– in this case, a colour– only increases the cognitive load.

    Who knows? It may someday be you who has to go back and revise your CSS.

    Programmers like to say that you have to be smarter to fix a broken program than it was to write the program in the first place. If you write at the limits of your cleverness, you are by definition not clever enough to fix it if it doesn’t work. Having multiple descriptions for a colour is one of those “clever” techniques that makes it hard to find and fix problems later.


  30. squid Says:


    Hi Elf, I am inclined to agree with you on this - I think that sites should maintain a longer format of the CSS file where all elements are consistently named/formatted and another file which is compressed as far as possible. Whether it is practical to do this in practise depends on how you organise your development - automated build tools certainly help.


  31. WebGyver Says:


    Great stuff. You know, this kind of information usually takes a while to collect and figure out — unless you happen to work with a guru who knows everything. Thanks for putting this together.

    Question: Sometimes, I see three values in a top, right, bottom, left scenario. For example:

    margin: 2px 4px 6px;

    What’s the significance of that? (And I’ve seen it often enough from different sources to know that it’s not a typo.)

    And by the way, what’s the deal with underscores and hyphens in class or selector names? Are those still taboo?

    Just wondering.


  32. frog Says:


    If you only declare two or three values, the undeclared values are taken from the opposing side.

    margin: 10px 20px; /* 2 values */
    Top and bottom is 10px, left and right is 20px

    margin: 10px 20px 30px; /* 3 values */
    Top is 10px, left and right is 20px and the bottom margin is 30px;

    Also underscores and hyphens in class, ID and selector names are just down to the developer coding the CSS/XHTML, they have no relevance. I guess you can call them what you will :)


  33. [root@EGA]# » Blog Archive » links - 20081002 Says:


    [...] TITLE!! The Frog Blog » 10 CSS shorthand techniques you’ll use everyday Body Border 2: Fade In with Gradient - CSS-Tricks Quick IE6 Fixes - Webmonkey The Fed just released [...]


  34. JeremiahTolbert.com » Blog Archive » links for 2008-10-03 Says:


    [...] The Frog Blog » 10 CSS shorthand techniques you’ll use everyday (tags: css webdesign forblog) [...]


  35. Link Post Sunday 10/5 | Mr Sun Studios Says:


    [...] 10 CSS shorthand techniques you’ll use everyday by The Floating Frog [...]


  36. Daily Del.icio.us Says:


    [...] Del.icio.us The Frog Blog » 10 CSS shorthand techniques you’ll use everyday Ten Drupal 6 modules for every site | …himerus …himpressive Audit Files - Drupal [...]


  37. Matthew Says:


    thank u r information

    it very useful

    u r blog Is very nice


  38. Links for 2008-10-26 [del.icio.us] | Blog do Camillo - O dia-a-dia de um Desenvolvedor Web Says:


    [...] 10 tecnicas de css para  nosso dia-a-dia [...]


  39. The Frog Blog » CSS for ABSOLUTE BEGINNERS - shaping up with CSS Says:


    [...] guess your too good for this, it’s like child’s play, right? Well have a look at this, 10 CSS shorthand techniques you’ll use everyday, it will be more up your [...]


  40. Link Love Time! SEO Forecasting, SEM Tools, Free Ivy League Business Courses And More | SEO ROI Services Says:


    [...] 10 CSS shorthand techniques you’ll use everyday [...]


  41. lillbra » Blog Archive » 4 css-tips jag INTE följer Says:


    [...] bl.a. i: 10 CSS shorthand techniques you’ll use everyday Jag tycker att universalselektorn (*) oftast inte behöver användas. För browser-reset använder [...]


  42. Ian Hutchinson Says:


    It took me forever to remember the order of the values in the margins and padding shorthands


  43. With great power comes great responsibility | qrisper Says:


    [...] Big mistake that was.  Spent a few hours fixing all of the damage I caused.  I found the tips from David’s old blog.  Actually found a number of good resources…a few of which I [...]


  44. 10 CSS shorthand techniques | just4freaks.de Says:


    [...] CSS shortland is a technique of writing mulitple declarations and values in a single line of CSS code. The advantages of using shorthand is to primarily reduce the CSS file size, but there are other benefits. A bloated and disorganised stylesheet can be hard to debug if you encounter problems, especially if you wrote it and another unfortunate colleage has to fix it while your away sunning it in some hot climate. CSS shorthand techniques [...]


  45. we4 design studio Says:


    Man I loved your blog has great tips on css, so its great job, congratulations.

    we4 design studio’s last blog post..Bilheteria Brasília Shopping


  46. 84 Amazingly Useful CSS Tips & Resources | Hi, I'm Grace Smith Says:


    [...] 10 CSS shorthand techniques you’ll use everyday [...]


  47. 84 Amazingly Useful CSS Tips & Resources | Grace Smith | cssOrigins.com Says:


    [...] 10 CSS shorthand techniques you’ll use everyday [...]


  48. ryanm Says:


    This is very useful post. Shorthand really makes your work easy and can save time. Nice post


  49. 84 recursos y consejos sobre CSS « GoVisual Says:


    [...] 10 CSS shorthand techniques you’ll use everyday [...]


  50. 10 CSS Shorthand Techniques You’ll Use Everyday | Design Newz Says:


    [...] 10 CSS Shorthand Techniques You’ll Use Everyday [...]


  51. Lethalogica Says:


    Nice list, only one I don’t use for everything is the font one.


  52. Louis Says:


    Nice list. Don’t forget to mention that if you use the “font” shorthand, you have to put the different properties in a specified order, otherwise they won’t work. Which is basically why I personally don’t use that one.

    Louis’s last blog post..How To Put a Multi-Line Indent on a Styled Blockquote


  53. James Says:


    Nice tips… ever since I learned CSS, I’ve been doing things the hard way until the other day a friend told me it was messy, so I better get my act together…. =P




Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CommentLuv Enabled

©2006 - 2009 The Floating Frog