Cover

CSS for the XAML Guy - Positional Selectors

May 3, 2012
No Comments.

I got into a longish, public discussion last night about XAML versus the HTML/CSS stack last night. I think they both have merit and pros and cons but it made me decide to add a short series of posts that highlight some of the CSS things that surprised me most (like my JavaScript for the C# Guy posts - and yes, more of those are coming too).

The first topic I am covering is some subtleties of the selector syntax. CSS selectors allow you to pick children, descendants and adjacent siblings. I found that I used descendant selector quite a lot:

#main h1 /* descendant */
{
  color: Red;
}

```csharp

This syntax effectively says, any **h1** inside an element named "**main**". I see people assume this actually means, \*directly\* inside the "**main**" element. So if you had some HTML like this, all **h1**'s inside "main" would be colored red:


```xml
<!DOCTYPE html>
<html>
<body>
  <h1>Top</h1>
  <section id="main">
    <h1>Main Level</h1>
    <section id="article">
      <h1>Second Level</h1>
      <p>Yup</p>
    </section>
  </section>
</body>
</html>

Note that it applies to all the descendants. But but if you did want just the h1’s directly inside (or…ahem a child) of “main”? That’s child selector syntax:

#main > h1 /* child */
{
  font-size: 24px;
}

```csharp

Then only the **h1** containing "**Main Level**" will have the rule applied. I've seem some CSS with tons of "!important" to override the descendant syntax because they didn't seem to know about child selector.

The last one is the adjacent sibling selector. This selector looks for elements that are directly next to each other (or...ahem...adjacent):


```css
h1 + p /* adjacent siblings */
{
  border-bottom: black 2px solid;
}

```csharp

In this case, the **p** (not the **h1**) will have a border under it. The other **h1**'s will be left unmolested. Here's a complete example if you want to play:
<iframe style="height: 300px; width: 100%" src="http://jsfiddle.net/Lz6ck/embedded/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
"If you're not careful, you just mind learn something..."