Adjacent Sibling Selectors and IE

Author: Dave Cassel  |  Category: Software Development

I came across an interesting little gotcha today while working with CSS’ adjacent sibling selectors. First, a quick intro, in case you’re not familiar with them.

<div class="content">
  <h1>Big News</h1>
  <p>Intro paragraph.</p>
  <p>Meaningless drivel</p>
</div>

Sibling selectors let you apply styles to an element based on what it’s next to, rather than the usual way of what it’s in. So in this case, I could apply this style:

h1 + p {
  font-weight: bold;
}

making the intro paragraph bold while leaving the second one alone. Very handy.

What I got stuck on for a bit was that I had this technique working in Firefox, but it wasn’t working in Internet Explorer. A little research confirmed that IE7 supports it, but its support is buggy. I figured I must have stumbled into one of the bug cases, but the listed ones didn’t apply. To make a long story short, here’s what happened: Firefox was more forgiving and overlooked my error; IE did not. My first sibling contained an element with a typo: the closing tag didn’t match the opener. Firefox figured out what was supposed to be going on, and allowed the selector to match. IE got confused, and so it didn’t match. Here’s a simplified version:

<div class="content">
  <div>
    <span>Look at me!</xpan>
  </div>
  <div>
  </div>
</div>

The <span></xpan> mistake got me messed up. So if you use adjacent sibling selectors and IE doesn’t want to play, check your syntax — you might just have made a simple mistake in there somewhere.

Tags: , , ,

Leave a Reply