Monday, June 30, 2008

Using the ~ selector in CSS

So Eric Wendelin is wondering what can be done with the CSS3 indirectly-adjacent sibling selector, now that the majority of browsers actually support it. Here are some ideas off the top of my head:

Minimalist horizontal menus

<style type="text/css">
ul {list-style:none;margin:0;padding:0;}
li {float:left;}
li ~ li {border-left:1px solid #000;}
  <li><a href="#">Home</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>

The code above puts borders in all menu items, except the first. Like so:

This same idea can be applied for other menu layouts (it's particularly useful for boxy, multi-level left menu designs.)

Equally spaced 3-column layout

.column {background:#eee;float:left;width:32%;}
.column ~ .column {margin-left:2%;}
<div class="column">Text</div>
<div class="column">Text</div>
<div class="column">Text</div>

Pretty self-explanatory, I hope :)

Sematic Inference

Say you have a blog:
<style type="text/css">
h1 ~ p {/*article styles*/}
h2 ~ p {/*comment styles*/}
<h1>Using the ~ selector in CSS</h1>
<p>Bla bla bla, Leo talks too much.</p>
<p>lolol photoshopped</p>

Much cleaner than wrapping divs everywhere, huh?

Anything else?

I'm sure there are plenty of other cooler ways to use this selector. Now that Microsoft has announced that it will no longer sell XP, IE6 will become less and less of a concern and I expect web developers to start exploring new CSS techniques more.

If you got more ideas, post them up :)

1 comment:

  1. I really like the idea with the menu styles. this could make css code much more readable in the future.