Wednesday, May 20, 2009

10 Best CSS Practices to Improve Your Code

It’s really easy to find yourself wondering how your CSS got to be such a mess.

Sometimes it’s the result of sloppy coding from the start, sometimes it’s because of multiple hacks and changes over time.

Whatever the cause, it doesn’t have to be that way. Writing clean, super-manageable CSS is simple when you start off on the right foot and make your code easier to maintain and edit later on.

Here are 11 tips for speeding up the process, writing CSS that is slimmer, faster and less likely to give you a headache.

1. Stay Organized

Just like anything else, it pays to keep yourself organized. Rather than haphazardly dropping in id’s and classes in the order in which they come to mind, use a coherent structure.

It will help you keep the cascading part of CSS in mind and sets your style sheet up to take advantage of style inheritance.

Declare your most generic items first, then the not-so-generic and so on. This lets your CSS properly inherit attributes and makes it much easier for you to override a specific style when you need to. You’ll be faster at editing your CSS later because it will follow an easy to read, logical structure.

Use a structure that works best for you while keeping future edits and other developers in mind.

  • Resets and overrides
  • Links and type
  • Main layout
  • Secondary layout structures
  • Form elements
  • Miscellaneous

Screenshot

2. Title, Date and Sign

Let others know who wrote your CSS, when it was written and who to contact if they have questions about it. This is especially useful when designing templates or themes.

Screenshot

Wait a minute… what’s that bit about swatch colors? Over the years, I’ve found that adding a simple list of common colors used in my style sheets is extremely helpful during initial development and when making edits later on.

This saves you from having to open up Photoshop to sample a color from the design, or look up colors in the site’s style guide (if it has one). When you need the HTML code for that specific blue, just scroll up and copy it.

3. Keep a Template Library

Once you’ve settled on a structure to use, strip out everything that isn’t generic and save the file as a CSS template for later use.

You can save multiple versions for multiple uses: a two-column layout, a blog layout, print, mobile and so on. Coda (the editor for OSX) has an awesome Clips feature that lets you do this easily. Many other editors have a similar feature, but even a simple batch of text files will work nicely.

It’s insane to re-write each and every one of your style sheets from scratch, especially when you’re using the same conventions and methodologies in each.

Screenshot

4. Use Useful Naming Conventions

You’ll notice above where I declared a couple of column id’s and I called them col-alpha and col-beta. Why not just call them col-left and col-right? Think of future edits, always.

Next year you may need to redesign your site and move that left column to the right. You shouldn’t have to rename the element in your HTML and rename the id in your style sheet just to change its position.

Sure, you could just reposition that left column to the right and keep the id as #col-left, but how confusing is that? If the id says left, one should expect that it will always be on the left. This doesn’t leave you much room to move things around later on.

One of the major advantages of CSS is the ability to separate styles from content. You can totally redesign your site by just modifying the CSS without ever touching the HTML. So don’t muck up your CSS by using limiting names. Use more versatile naming conventions and stay consistent.

Leave position or style specific words out of your styles and id’s. A class of .link-blue will either make more work for you, or make your style sheet really messy when your client later asks you to change those blue links to orange.

Name your elements based on what they are, not what they look like. For example, .comment-blue is much less versatile than .comment-beta, and .post-largefont is more limiting than .post-title.

5. Hyphens Instead of Underscores

Older browsers like to get glitchy with underscores in CSS, or don’t support them at all. For better backward compatibility, get into the habit of using hyphens instead. Use #col-alpha rather than #col_alpha.

6. Don’t Repeat Yourself

Re-use attributes whenever possible by grouping elements instead of declaring the styles again. If your h1 and h2 elements both use the same font size, color and margins, group them using a comma.

This:

Screenshot

You should also make use of shortcuts whenever possible. Always be on the lookout for opportunities to group elements and use declaration shortcuts.

You can accomplish all of this:

Screenshot

with only this:

Screenshot

It’s very important that you understand the order in which CSS interprets these shortcuts: top, right, bottom, left. A big clockwise circle, starting at noon.

Also, if your top and bottom, or left and right attributes are the same, you only need to use two:

Screenshot

This sets the top and bottom margins to 1em, and the left and right margins to 0.

7. Optimize for Lightweight Style Sheets

Using the above tips, you can really cut down the size of your style sheets. Smaller loads faster, and smaller is easier to maintain and update.

Cut out what you don’t need and consolidate wherever possible by grouping. Use caution when using canned CSS frameworks as well. You’re likely to inherit lots of bulk that won’t be used.

Another quick tip for slim CSS: you don’t need to specify a unit of measure when using zero. If a margin is set to 0, you don’t need to say 0px or 0em. Zero is zero regardless of the unit of measure, and CSS understands this.

8. Write Your Base for Gecko, Then Tweak for Webkit and IE

Save yourself troubleshooting headaches and write CSS first for Gecko browsers (Firefox, Mozilla, Netscape, Flock, Camino). If your CSS works properly with Gecko, it’s much more likely to be problem free in Webkit (Safari, Chrome) and Internet Explorer.

9. Validate

Make use of W3C’s free CSS validator. If you’re stuck and your layout isn’t doing what you want it to do, the CSS validator will be a big help in pointing out errors.

10. Keep a tidy house

Separate browser-specific CSS to its own individual style sheet, and include as needed with Javascript, server-side code or conditional comments. Use this method to avoid dirty CSS hacks in your main style sheets. This will keep your base CSS clean and manageable.

Friday, May 15, 2009

Simple Page Peel Effect with jQuery & CSS

You have probably seen these forms of advertisings where you can peel a corner of a website and see a message underneath. It seems most are flash driven, but I decided to try it out using some simple lines of jQuery.

Page Peel Effect with jQuery and CSS

1. HTML - Page Peel Wireframe

The “pageflip” div will act as the container, mainly used to establish the relative positioning. Then nest the image and the span class of “msg_block” wrapped in an tag. Note - If you don’t have any conflicting absolute/relative positioning properties, you technically don’t need the “pageflip” container at all.

2. CSS - Page Peel Styles

Set the image property to a smaller size (50px by 50px) by default and set the absolute positioning to be in the top right corner. The image will be used similar to the “masking” technique in Photoshop or Flash, where it will be placed on top of the hidden message, so only a portion of the message will be shown. Check out the image below for a visual:

Page Peel Effect with jQuery and CSS

The actual message behind the “peeling” effect, is all within the “msg_block” class. By default, it will start at 50px by 50px, positioned on the top right corner of the page. The text-indent will shoot the text off of the page for anyone with CSS enabled.

Code

#pageflip {
position: relative;
}
#pageflip img {
width: 50px; height: 52px;
z-index: 99;
position: absolute;
right: 0; top: 0;
-ms-interpolation-mode: bicubic;
}
#pageflip .msg_block {
width: 50px; height: 50px;
position: absolute;
right: 0; top: 0;
background: url(subscribe.png) no-repeat right top;
text-indent: -9999px;
}

Note that the “msg_block” height is off by 2px compared to the image property - this is taking in consideration of the drop shadow that the image has.

3. jQuery - Animating Page Peel

All we are doing here is expanding the image and msg_block on hover, then retracting to its default size on hover out.

Code

$("#pageflip").hover(function() { //On hover...
$("#pageflip img , .msg_block").stop()
.animate({ //Animate and expand the image and the msg_block (Width + height)
width: '307px',
height: '319px'
}, 500);
} , function() {
$("#pageflip img").stop() //On hover out, go back to original size 50x52
.animate({
width: '50px',
height: '52px'
}, 220);
$(".msg_block").stop() //On hover out, go back to original size 50x50
.animate({
width: '50px',
height: '50px'
}, 200); //Note this one retracts a bit faster (to prevent glitching in IE)
});

Conclusion

The concept is very simple and may come in handy one day. If you have any questions or know of other techniques, please don’t hesitate to let me know~

Page Peel Effect with jQuery and CSS

7 Powerful image carousels for web designers.

This post is a collection of some powerful carousels for images and text content ready to use in your web projects. It includes Agile Carousel, YUI Carousel, JCarousel, iCarousel (jQuery + MooTools) and a tutorial about how to implement a simple Flickr-like carousel using Prototype-UI.

f you want to suggest other interesting scripts about this topic, please leave a comment. Thanks!

1. Agile Carousel
Agile Carousel is a jQuery plugin that lets you create a super fexible carousel with advanced setting options. It supports text and images in each box and a navigator to display in which box you are. Take a look here to see it in action, it's absolutely my favourite!

2. Yahoo! UI Carousel Control
The YUI Carousel Control provides a widget for browsing among a set of like objects arrayed vertically or horizontally in an overloaded page region. The "carousel" metaphor derives from an analogy to slide carousels in the days of film photography; the Carousel Control can maintain fidelity to this metaphor by allowing a continuous, circular navigation through all of the content blocks.

3. jCarousel
jCarousel is a jQuery plugin for controlling a list of items in horizontal or vertical order. The items, which can be static HTML content or loaded with (or without) AJAX, can be scrolled back and forth (with or without animation).

4. jCarousel Lite
jCarousel Lite is a jQuery plugin that carries you on a carousel ride filled with images and HTML content. Put simply, you can navigate images and/or HTML in a carousel-style widget. It is super light weight, at about 2 KB in size, yet very flexible and customizable to fit most of our needs.

5. Simple images carousel to create Flickr-like slideshows
This tutorial illustrates how to implement a simple images carousel to create a Flickr-like slideshow using Prototype-UI framework.

6. iCarousel
iCarousel is a powerful carousel built over MooTools v1.1 fully configurable from the user just in some steps. You can change any default option just initializating the class with an object in JSON. It's tested in Internet Explorer, Firefox, Opera and Safari.

7. Carousel.us
Carousel.us is an advanced Javascript 3D carousel which uses either MooTools framework and Reflection.js by Christophe Beyls, or Prototype.js and Script.aculo.us frameworks with Reflection.js. Take a look here to see it in action.