Wednesday, March 14, 2012

Slim Up Your HTML with CSS3 - Sliding Doors

The sliding doors technique, as made famous by an old article, has been an incredibly handy way to make buttons and tabs that can stretch dynamically based on the text. So as I've been studying CSS3, I've wondered what new features would allow us to slim up the markup. Let's take a look!

If you're not already familiar with the technique, you should read the original article. Here's the short version for those of you who just need a little memory jogging. Personally I like memory jogging better than "jogging" jogging, because you don't have to put on your shoes or stretch for ten minutes. But whatever.

The sliding doors technique uses two images. The first is generally a very small image of the left side of your tab or button, and the second is the rest of the image -- the right side. For example:

CSS Sliding Doors Equation

Take a look at Exhibit 1. This is the classic way of doing sliding doors.

We're dealing with two elements here -- one outer div that has the left image, and the anchor tag that has the right side image. The CSS isn't too involved. We've got the background-image on each element with a pinch of padding so our text has a little breathing room.

As markup goes, that's not terribly obtrusive. But as I've been learning CSS3, I've been really interested in finding ways to eliminate extra tags and classes as much as possible. So we're going to slim this up to just a single anchor tag.

The CSS3 magic is quite simple -- you can set more than one background image on a single element! Here's what it looks like:

As you can see, now both images are on the same element, so there's no need for the outer div. The values of the background property are simply separated by a comma. Rather than using the shorthand background property, you could also split them up (e.g., background-image, background-repeat, background-position) -- just make sure you keep the order of the values consistent.

No comments:

Post a Comment

Profile Picture
Dave Leeds
My Hobbies:
  • Programming
  • Cartooning
  • Music Writing
Full Profile