Archive from Apr 2008
CSS Attribute Selectors: Built-In Classes

If you’ve been a CSS groupie or follower of this website for any length of time, you should have a fairly firm grasp on the concept of using classes in XHTML as “hooks” into your pages (and if not, this article is a good place to catch up). But classes and IDs aren’t the only ways you can describe the elements in your website in order to style them. You can also make use of attribute selectors.
Attributes are the property=”value” pairs inside of most XHTML elements that further describe that element. Take the anchor tag, for example:
<a href="page.html" title="Click to visit!">Text</a>
This anchor tag has two attributes: href and title. Those attributes also have very specific values associated with them. And it’s these attributes, and their values, that make attribute selectors work.
By using attribute selectors in your CSS, you’re able to target elements with specific attributes, or even specific values within those attributes. When using attribute selectors, the attribute is contained within [brackets], just like how .classes have a leading period, or #ids have a leading pound sign. There are four ways to use attribute selectors:
The [attribute] syntax is the least specific of the four. It allows you to target any element with a specific attribute set, regardless of its value. For example:
a[title] {
font-weight: bold;
cursor: help;
}
This little bit of CSS would target any anchor tag that had a title attribute set, regardless of what the title contained. My CSS here makes the anchor boldfaced, and changes the cursor to a question mark when the user hovers over the link. This could be useful to indicate to the user that more information (i.e., the tool tip) is coming.
The most specific syntax is [attribute=”value”]. Using this selector, you’d be able to apply specific styles to elements with specific values set. So if, for example, you had an anchor that pointed to a specific website you wanted to emphasize:
a[href="http://www.cssnewbie.com/"] {
font-size: 120%;
color: red;
}
This code would add a bit of emphasis to any link going to the front page of CSSnewbie. I would recommend copying and pasting this code into any website you happen to be working on at the moment. :)
The [attribute~=”value”] syntax allows you to look within the attribute’s values and find a specific value within a space-separated list of values. Alternatively, you can use the related [attribute|=”value”] syntax to find parts of a value that are separated by hyphens (instead of spaces). So, for example, if I had an image with an alt tag that read “Gallery: Wombats Gone Wild,” I could style this gallery (and all other galleries that followed this same pattern) like so:
img[alt~="Gallery:"] {
border: 2px solid #333;
}
And suddenly, all of your images that link to galleries have special styling, without having to add any additional classes! And that’s really the beauty of attribute selectors: if used properly, they can be a great help in the fight against Classitis.
Of course, attribute selectors don’t work everywhere (why would they? They’re too cool for school). Here’s where attribute selectors earn a big fat FAIL:
- IE6 or below on the PC
- IE5 or lower on the Mac
- Netscape 4 or under (i.e., people in 1997)
- Both people still using Opera 3
Luckily, very few people are still using Opera 3, Netscape 4, or IE5. And with the recent release of IE7 (and the planned future release of IE8), Internet Explorer version 6 should be on its way out the door, as well. In other words, attribute selectors are fast becoming a reasonable means of styling your websites.
6 Great Wordpress Plugins Behind CSSnewbie

Maintaining a site as complex as CSSnewbie requires a bit more than just fancy CSS footwork. It also relies on a Content Management System (CMS) – Wordpress, in this case – and a healthy dose of plugins to extend that CMS’s capabilities. Here are six of the many Wordpress plugins that help keep CSSnewbie growing and thriving.
cforms II
The cforms plugin helps you build complex contact forms and embed them in your Wordpress site – all from the Wordpress back-end. I use this plugin on my contact page, and my advertising page. The plugin is amazingly customizable, both from within Wordpress and by manipulating the CSS the plugin uses. Although, I have to admit I haven’t done a lot of modifications to the forms’ CSS yet.
Comment Relish
Comment Relish is a great way to encourage interaction between your site’s readers and authors. The concept is pretty simple: each time a new person comments on your website, this plugin automatically sends them an email of your devising. You could theoretically use this plugin to inform your new community members of just about anything – a new e-book, perhaps, or other sites you run that they might be interested in visiting. I’m currently using it to thank my users for their comment and encourage them to comment again (and subscribe to my feed, if they haven’t done so already).
Using this plugin has been an overwhelmingly positive experience for me. Many commenters have responded to the email to tell me they appreciate the articles I’ve produced and to show me the work they’re producing in CSS. If you’d like to see the plugin in action, just leave a comment, and you should get an email at the address you specify fairly quickly.
Google XML Sitemaps
My content is only useful if people are able to find it, and search engines are the number one way most people start looking for new information. Thus, it pays to make sure your site is being properly indexed by search engines. One of the easiest ways to ensure you show up in the world’s most popular search engine (Google, for those counting) is to use the Google XML Sitemaps plugin.
This handy-dandy little plugin automatically creates an XML-based file describing your site’s content that you can then submit to Google. Once you tell Google where your sitemap resides, they’ll use it to ensure they’re fully indexing your website. And every time you post a new article, the plugin updates your sitemap. Organic Google searches are a growing segment of my inbound traffic, and I have no doubt that this plugin has a fair bit to do with that growth.
Redirection
Of course, all the search results in the world won’t do a bit of good if you reorganize your website and don’t leave a forwarding address for your users. About a month ago, I rethought my article permalink structure – I decided having the article’s “primary category” in the permalink wasn’t useful, as most articles belonged to several categories, and I didn’t consider one any more “primary” than the others. Unfortunately (in a way), Google had already indexed my site, and people were visiting from other sites via several soon-to-be-incorrect links. That’s when the Redirection plugin saved my rear.
All I had to do was describe to the plugin what my old permalink structure looked like, and what my new one now looked like. It took care of all of the forwarding stuff in the back end. I was worried the process of setting up a redirect file would take me most of the afternoon… but it ended up taking me all of ten minutes.
SEO Meta Editor Advanced
And while we’re on the topic of making sure your users can find your content, a little search engine optimization (SEO) can make a big difference, too. Wordpress already does a pretty good job with SEO just by providing clean, well-written code in their included templates and making “friendly” URLs the default for all new installations. However, there’s more that can be done in terms of metadata, and for that, I turn to the SEO Meta Editor Advanced plugin.
The plugin adds a couple of extra fields to each post that I write, allowing me to specify a group of meta keywords and a description. The keywords help search engines categorize my articles and increase the chances of someone finding the information they want. Search engines also use the “description” field to describe your pages instead of just grabbing an excerpt from your article that may or may not be descriptive. This is particularly useful for someone like me, because I can be a bit wordy at times (this time, for example). The description field ensures that people coming in off search engines get a good, concise summary of the article they’re clicking through to.
Snippet Highlight
The fundamental purpose behind CSSnewbie is to help people learn more about CSS. To do that, I often turn to code snippets to explain concepts or describe techniques. However, a snippet of code all by itself can be difficult to read – especially once the snippet is more than a few lines long. The Snippet Highlight plugin helps out by colorizing my code examples. It’s what turns this:
p {
font-weight: bold;
color: #333;
text-transformation: uppercase;
}
Into this:
p {
font-weight: bold;
color: #333;
text-transformation: uppercase;
}
The plugin can also add line numbers to your code snippets, but I personally found them a little distracting, so I modified the plugin’s CSS to exclude the line numbers.
These are just six of the many plugins that help keep CSSnewbie running – but these six I tend to rely upon more heavily than the others. I’m constantly trying out new plugins in the background to see if they could make the site more useful. If you know of any plugins that you think would be a good match for the site, please let me know about them in the comments!
Level the Playing Field with Reset Style Sheets

Scott Phillips is a web developer working at Drake University in Des Moines, Iowa.
The most frustrating part of learning cascading style sheets is getting consistent results across browsers. As you probably know, not every browser supports every rule in the same way (or at all).
Luckily, strategies have emerged that can help CSS newbies keep their sanity. The first is to write CSS so that it works in a browser that has solid support for CSS (like FireFox or Opera) and later tweak it, as needed, to work correctly in others (like IE6). Another strategy is to use a validator to find any simple syntax mistakes. These days, more and more developers are using a reset style sheet to cancel out pesky differences between browsers.
What’s the problem?
Even when you don’t use CSS in your web pages, you are still using CSS in your web pages. Huh? I’ll explain. Begin with the simplest page you can imagine:
<html> <h1>Here is my title.</h1> <p>Here is my paragraph.</p> </html>
View it with several browsers and you’ll see subtle differences. The margins are off. The font sizes and weights are different. We’ve hardly begun and already our pixel-perfect design is breaking down!
Here is what’s happening. Every browser has built-in default styles. To see Firefox’s on Windows XP, for example, open the file C:\Program Files\Mozilla Firefox\res\html.css. You’ll find rules like this:
h1 {
display: block;
font-size: 2em;
font-weight: bold;
margin: .67em 0;
}
...
blockquote[type=cite] {
display: block;
margin: 1em 0px;
padding-left: 1em;
border-left: solid;
border-color: blue;
border-width: thin;
}
...
hr {
display: block;
height: 2px;
border: 1px -moz-bg-inset;
margin: 0.5em auto 0.5em auto;
}
The lesson is this. If you don’t express an opinion about how an element should look, the browser will substitute its own. We’ve already seen that browsers never agree. Furthermore, even if an element looks identical across browsers, you can’t assume it is actually being treated identically (i.e. one browser may use a default margin for the white space around a list while another uses padding). Make a seemingly small adjustment and suddenly they both change in different ways. What a mess.
What can we do?
Zero-out the default browser styles. Then replace them with your own. A very simple reset rule looks like this:
* {
margin: 0;
padding: 0;
}
That cancels out margin and padding for all elements on the page. From here you might want to continue by resetting font sizes and removing image borders:
html {
font-size: 1em;
}
body {
font-size: 100%;
}
:link img, :visited img {
border: 0;
}
It would also be handy to fix inconsistencies with lists and tables:
table {
border-collapse:collapse;
border-spacing:0;
}
ol,ul {
list-style:none;
}
Slap all that code into a file called reset.css and @import it at the top of every page. You are on your way to more consistent results and fewer debugging headaches.
Standing on the Shoulders of Giants
Our reset style sheet is simple but effective but it’s just the beginning. The universal selector (*) can occasionally cause issues of its own. And inheritance problems can also crop up as you continue to expand your reset style sheet.
Luckily, web pros like to share. Yahoo has released their own reset style sheet for us to use, called Reset CSS, as a part of the larger Yahoo User Interface (YUI) library. Eric Meyer, a full-fledged CSS Jedi, has also done a lot of work on a robust reset style sheet. Both are excellent, and I recommend studying and adopting either (or parts of both) of them into your own projects.
Using Definition Lists: Question & Answer formatting

This guest article was written by Chris Coyier of CSS-Tricks, a site featuring tips, tricks, and tutorials on web design.
Unordered lists seem to get all the love these days, but there are just some things that are better semantically described with definition lists. Never heard of them? I’m not surprised. Here is the basic syntax:
<dl>
<dt>Definition Term</dt>
<dd>Definition Description</dt>
</dl>
There are two big differences between unordered lists and definition lists. One, there are two different elements that belong in a definition list: dt’s & dd’s. In unordered lists, all you have is li’s. Two, the only default styling applied to definition lists is a bit of a left-margin to the dd elements — no bullets or other strange positioning to fight.
Having two different tags to work with is what makes definition lists valuable. Take for example the need to create a FAQ’s page with a bunch of questions and their answers. Each question and answer group would really benefit from having a parent element, because then you could, for example, control the spacing between them or perhaps apply a border to visually separate them.
Many people would go straight for the div. With something like:
<div class="qa">
<h4>Question</h4>
<p>Answer</p>
</dl>
The problem with this is that div’s are very commonly used. Chances are, your page is already using several so it’s likely you will need to apply an unique class to the div to style it individually.
Other people will go straight for the unordered list:
<ul>
<li class="question">Question</li>
<li class="answer">Answer</li>
</ul>
The problem with this is that since you only get li elements in your ul, you will need to apply unique classes to them in order to get different styling.
I propose that the best elements to use for something like question/answer content is the definition list:
<dl>
<dt>Question</dt>
<dd>Answer</dt>
</dl>
Will using a div or an ul work? Sure, they’ll work just fine and nobody is going to slap your hand for using them. But if you want to be a super hip semantics junkie, you’ll use a definition list. You get all the advantages: a parent element for styling the whole group and different tags for the question and answer so they can be styled separately without needing to use unique classes. If needed, you can also use multiple dt’s and dd’s and use them in any order you wish.
Check out this example of a question and answer list using definition lists (click the image to see a live example):
Great Resources Elsewhere: April 12 to April 18
Jeremy Harrington is the user experience advocate and visual designer behind crawlspace|media, a creative design firm.
Designers Toolbox: OS Form Elements
Techniques for designing with type characters
Get Inspired!
Standards vs Quirks Mode

Aaron Webb is an IT professional working for a quickly growing IT services company. You can learn more about him at his website, The Webboy.
Web designers have long been plagued by the support (or lack thereof) of standards in the browser. One browser may interpret a CSS property or HTML tag one way while another may have a slightly or even largely varied implementation. Lately, thanks to the efforts of standards advocacy groups, browsers have been moving toward a more consistent support of the web standards. How then do you move into standards-compliance without breaking compatibility with the already billions of pages on the internet that may have not been designed to standards or contain various hacks to overcome deficiencies in the browser? Introducing the Doctype switch!
Doctype and Rendering Mode
First let’s explain doctypes. The doctype is the first thing that appears in a standards-compliant page. This tells the browser which DTD we are going to validate against when rendering our page. The W3C has set forth specifications that lay out the rules of which (x)HTML tags are acceptable and in which places. One of these specifications is called a DTD (Document Type Definition) and may be one of the following:
- HTML 4.01 Transitional
- HTML 4.01 Strict
- HTML 4.01 Frameset
- XHTML 1.0 Transitional
- XHTML 1.0 Strict
- XHTML 1.0 Frameset
- XHTML 1.1
A doctype has a reference to which DTD this document will validate to. We may specify a doctype in our xHTML page which is targeting XHTML 1.0 Transitional compliance. In this case our doctype will look something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
The first part of this string specifies the type of document we are working with. The second part is called a “public identifier” specifying the DTD used and the last part is the “system identifier” which is a URL to the actual dtd used for validation. Below are some further examples of using the doctype with various specifications.
HTML 4.01 Strict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
XHTML 1.0 Strict
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
XHTML 1.0 Frameset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
So now that we understand doctype, what exactly is a rendering mode and how does the doctype effect it? We refer to the rendering modes as simply “quirks” and “standards”. When a browser renders a page in “standards” mode it will validate the code of that page against the chosen W3C specification. If the markup is invalid or not well-formed the page may render incorrectly or not at all. On the other hand, if “quirks” mode is used, the browser will do its best to parse a page even if the markup is not well-formed and will render the page the best that it can even if there is invalid markup.
The doctype comes into play in instructing the browser which mode it should use to render the page. To use “standards” mode, simply specify one of the doctypes we mentioned before. When the browser encounters these doctypes it will enter standards mode and render according to the specified DTD. If we omit the doctype entirely - and many existing pages on the web do not contain one - or specify an invalid one, then the browser will enter “quirks” mode and render the page in the traditional fashion. It may be worth it to note that the use of something other than a Strict DTD, such as a Transitional DTD, does not imply “quirks” mode. A transitional DTD is a valid specification and will be validated to that standard.
Variations and Quirks
So if I use a correct doctype and specify a valid DTD, then all my problems will be solved, and I will code in web nirvana right? Wrong! There are several quirks (no pun intended) even in this. When using standards mode, the slightest mistakes can make for a long time in finding a simple problem. Thankfully most development tools can easily locate these, and the validators show errors in the documents that may point to rendering errors. Let’s take a look at a few nuisances.
Many people writing XHTML markup will insert an xml declaration at the top of their document. When used, this declaration must be the first line in the document. This declaration is not required and will throw IE6 and Opera 7 into “quirks” mode as they require the doctype declaration to be the first line in the document. There have been arguments over the necessity of the xml declaration, but it is easiest to just leave it out and enjoy standards mode across the board.
Another variation is that with Mozilla browsers a third rendering mode, “almost standards”, is introduced. Fortunately the differences are small and the only effected parts of a document are images contained within table cells, but then after this standards-compliant talk the cases of this table-based layout will surely be few and far between :-)
Conclusion
Hopefully you have gained a high-level understanding of how browsers will interpret your markup, and why your rendering results may vary. When writing with standards compliance, you will be able to acheive a greater consistency in the rendering of your pages across browsers. Use the resources below to narrow in on any of the topics mentioned above.
Jump-start Your Development With CSS Frameworks

Scott Phillips is a web developer working at Drake University in Des Moines, Iowa.
Do you get a feeling of déjà vu every time you begin a new web project? Do you smack your forehead trying to remember the best way to get something to render correctly in IE6? …again? Do you refer back to old sites when choosing font-families and sizes?
There is a better way.
Learning how to wield the mighty powers of CSS is important, but you don’t have start coding from scratch every time. CSS frameworks can save a lot of time and even make your site look better in the end.
What’s a framework?
CSS frameworks are like Legos. Combine their simple building blocks in thousands of different combinations to create a clean and usable layout for your site. Once these basic elements are in place, go wild adding your own custom headers, footers, backgrounds, bullets– whatever you’d like. All of the frameworks discussed in this article include support for multi-column layouts and readable typography. Some go further with classes for design elements like navigation menus, pull-quotes, lists, forms, and more.
How do I use them?
Generally speaking, all you need to do is add the framework’s classes to certain XHTML tags and include the needed CSS files in the header of your document. In a matter of minutes you’ll have an attractive (yet basic) layout. Of course, each framework has it’s own documentation, examples, and tutorials.
Pros
- Save time. This is the biggest advantage of using frameworks. They give you a huge head-start on your CSS. All of the tedious/boring stuff is done, freeing you to spend time on more creative things.
- Best practices. Many talented developers contribute to frameworks. Take advantage of their expertise. For example, the hot topics of Grid-based layouts and vertical rhythm are concepts borrowed from the print world. Even if you aren’t totally sure how they apply to the web, CSS frameworks can help you take advantage of them.
- Cross browser support. Convincing different browsers to render a design consistently has always been a pain. Frameworks have built-in fixes for the worst offenders.
Cons
- Not always semantically meaningful. A basic tenant of good web design is to separate presentation from content to produce readable and maintainable code. CSS frameworks require compromises that may get the purists among us a little upset.
- Bloated code. Do you really need support for 24 columns when you only use three? Probably not. In reality, however, the file sizes of all of these frameworks are reasonable. You could always strip out unused portions is file size is a really big concern.
- Don’t use it as a crutch. It’s important to understand what is happening under the hood of a framework. Each one has a learning curve. You’ll need to spend time understanding how they are built, their strengths and weaknesses, and how to customize them.
Popular Frameworks
Blueprint CSS

Blueprint CSS is my first choice in CSS frameworks. It is lightweight, easy to understand, and produces very attractive grid-based layouts with minimal effort. In addition, its typography choices (everything from headers to lists and addresses) are readable and attractive. It’s not perfect, however. Although Blueprint wasn’t the first one available, it has generated a lot of buzz and developed an active community since it’s release in August 2007. There is currently no built-in support for flexible-width layouts. I’ve found at least one online Blueprint CSS editor, but it’s not nearly as nice as the YAML’s (see below).
YUI Grids CSS

The Yahoo User Interface (YUI) library is a set of controls and utilities for creating rich interfaces for web applications. It is aimed primarily at the Javascript + Dom Scripting + Ajax crowd. A subset of the library essentially constitutes a CSS framework when used together. They are Grids CSS, Reset CSS, Base CSS, and Fonts CSS. YUI has been criticised having bloated code and requiring too many extra DIV tags. On the other hand, these are the very same libraries that Yahoo uses for some of their own large projects so they must be solid. Beyond the standard documentation, those of you with longer attention spans may want to watch the author, Nate Koechley, give a 42 minute overview presentation.
YAML

Yet Another Multicolumn Layout (YAML) is yet another framework worthy of serious consideration. In fact, it may become my go-to framework in the very near future. YAML hasn’t received the amount of attention that some other frameworks have due to the fact that it was originally written and documented in German. It should not be overlooked. A few of its many strengths include a focus on fluid layouts, exceptional documentation, and the truly impressive drag-and-drop YAML Builder.
960

960 Grid System is a newcomer to the scene. It is very similar to Blueprint but has different design considerations like wider margins. 960 also lacks a number of features that the author considers unnecessary (like a baseline font size). 960 includes printable grid paper and template files for Fireworks, Photoshop, OmniGraffle and Vision. Even if you don’t use the framework, these will make a handy edition to your web design arsenal.
Guest Authors on CSSnewbie
I’m going to be in Europe for the next two weeks. However, the show must go on, so in my stead I’ve rounded up several guest authors who will tackle various interesting topics while I’m away.
Over the next two weeks you’ll be reading guest posts from Scott Phillips, Chris Coyier, and Aaron Webb. They’ll be covering a diverse number of topics – from understanding the difference between Quirks and Standards mode, to learning the pros and cons of using CSS frameworks. Also, Jeremy Harrington will be stepping in to bring you great CSS resources from elsewhere around the web.
So have a great couple of weeks, one and all! I’ll be back in action April 28th. Until then, be sure to visit the guest authors’ websites, and give them a great conversation to look forward to here on CSSnewbie!
Great Resources Elsewhere: April 5 to April 11
25 Must Buy, Borrow, or Steal Books for Web Designers | Creating a blog design blog
klauskomenda.com » Collection of Web Developer Tools, per Browser
woork: Top-Down approach to simplify your CSS code
The CSS-Only Accordion Effect
The Accordion Effect is fast becoming one of the most commonly used (and perhaps abused?) effects of the Web 2.0 world. Most JavaScript frameworks make such an effect fairly easy to pull off – heck, MooTools even built their reputation on it in the early days. So what makes this accordion effect special? It doesn’t require a single line of JavaScript.
First off, what is an “accordion” effect? Generally speaking, the accordion effect takes several larger elements and then compresses them into a small space so that only a small portion (like a heading) of most or all of the elements is visible. Then, when the user interacts with that element — either by clicking on it or maybe only mousing over — the accordion expands so that the element of interest is visible, and the other elements shrink down automatically. When it’s in use, it looks a bit like an accordion expanding and contracting: hence the name.
Our accordion will work exactly the same way: all of the elements will be partially visible when the user loads the page. And then when they mouse over a particular section, it will instantly expand – and the other elements will contract – to make reading more easy.

So how do we accomplish this trick? First, we start with our XHTML, which just consists of a couple of divs with some IDs applied:
<div id="accordion"> <div id="part1"> <p>This text is in part 1.</p> </div> <div id="part2"> <p>This text is in part 2.</p> </div> <div id="part3"> <p>This text is in part 3.</p> </div> <div id="part4"> <p>This text is in part 4.</p> </div> </div>
My first div defines where my accordion starts and ends. The divs nested inside are just parts of my accordion – they don’t even technically need IDs unless I want to style them differently. That’s all the XHTML it takes!
So now, let’s start building our accordion. We start by defining the physical limitations of our space:
#accordion {
width: 500px;
margin: 100px auto; }
All I’ve done is give my accordion a specific width and centered it in the page for a nice visual effect. Now, I have to create the default state for the divs inside of my accordion:
#accordion div {
float: left;
width:25%;
height: 300px;
overflow: hidden;}
This snippet floats all of my divs to the left and gives them a specific width and height. I’ve chosen a width of 25% because I have four elements in my accordion, so they all split that width up evenly by default. If I’d had five elements, I would have used 20%, and so on. My height of 300 pixels also becomes the height of my accordion div.
The overflow: hidden part here is also crucially important. This is what prevents my divs from either resizing to fit their content or spilling their content out of the containing div and onto our page. It also creates a nice visual effect… people will wonder what content they’re missing, and will mouse over the area to investigate.

So now that we’ve created our default state, we need to create our hover or “active” state. This requires two CSS rules. The first looks like this:
#accordion:hover div { width: 20px; }
We’re using the :hover pseudo-class here in a pretty creative way – we’re telling all of the divs inside of the div we’re hovering over to change. Specifically, we’re shrinking them all down to 20 pixels to make room for our expanded accordion section. So now we just need to make sure it expands:
#accordion:hover div:hover {
width: 440px;
overflow: auto; }
The :hover pseudo-class comes into play here again. Now, we’re applying styles to an element we’re hovering over, inside of an element we’re hovering over. We’re styling this element differently than our others by giving it a specific width – 440 pixels, i.e. 500 pixels minus the 20 pixels taken up by our other three divs – and setting its overflow to “auto.” These two classes cause our active div to expand, and then give it a scroll bar if the content is too long.
And that’s all there is to creating a CSS-only accordion box! If you’d like to see it in action, click here. The only change I’ve made to the full version is I’ve added a few background styles and some interior padding to each of the accordion sections to make them stand out and look a little more attractive.
This example creates a horizontal accordion box. But it’s just as easy to create a vertically oriented accordion. All we really need to do is eliminate the floats on our nested divs and turn most of our width tags into height tags. Here is the markup:
#accordion {
width: 500px;
height: 400px;
margin: 20% auto; }
#accordion div {
height:25%;
overflow: hidden;}
#accordion:hover div {
height: 20px; }
#accordion:hover div:hover {
height: 340px;
overflow: auto; }
And you can see it in action here.
As with any trick this cool, there are some caveats. Most significantly: this technique does not work in IE6, because IE6 doesn’t support hover states on anything other than anchors. Therefore, you can make it work if you’re willing to make a sacrifice: if you wrap all of your divs in anchor tags, and then apply the hover state to those anchors instead of your divs, the technique should work the same (I haven’t tried it, though). However, that wouldn’t be particularly semantic or valid, so I’m not showing it here.
Also, if you apply any padding or borders to your #accordion div, that can cause some problems. The border and padding are part of your div, and therefore part of your :hover class. However, if you’re hovering over the containing div’s padding, you aren’t hovering over one of the sections of your accordion – meaning all of your interior divs will shrink down to their smallest size, and none will grow to fill the space. It took me half an hour of debugging to figure this one out. :)
So there you have it. Use it, share it, love it. And let me know in the comments if you come up with a particularly interesting or attractive implementation – mine is obviously pretty simple!















![Click here for more information. [your ad here] Become a Sponsor! Click here to learn more.](/img/your-ad-here.gif)