CSS Selectors

In addition to the class and ID selectors that we have used, CSS provides some powerful ways to specify what boxes you want certain CSS rules to apply to.

Decendents

This rule selects any h1 HTML element that falls inside a foo div:

     #foo h1 { color: red;}

So, given the following HTML...

     <div id="foo">
          <h1>This text should be red.</h1>
     </div>

...we get this result:

This text should be red.

Keep in mind that this rule will apply to all <h1>s that appear inside of #foo, no matter how deeply they're "buried." For instance...

     <div id="foo">
          <ul>
              <ul>
                  <ul>                  
                      <h1>This text will also be red.</h1>
                  </ul>
              </ul>                   
          </ul>
     </div>

Yields this:

Children

If we only wanted the h1s that are the first children of the div to be selected, we could use this rule instead:

 #baz > h1 { color: orange;}

So, given the following HTML...

     <div id="baz">
          <h1>This text should be orange.</h1>
     </div>

...we get this result:

This text should be orange.

This rule will only apply to the <h1>s that appear inside of #foo at the uppermost level. If they are burried any "deeper "in the HTML, the rule won't apply. For instance...

     <div id="baz">
          <ul>
              <ul>
                  <ul>                  
                      <h1>This text will not be orange.</h1>
                  </ul>
              </ul>                   
          </ul>
     </div>

Yields this:

Adjacent boxes

Suppose we have the following CSS rules:

.bar {border: thick blue solid;}

.bar + .bar {border: thick green solid;}

.bar + .bar + .bar {border: thick yellow solid;}

The first rule applies to the first instance of a .bar element. But if another .bar element follows it, the second rule will apply. Likewise for the third rule:

This is the first .bar element in a row. The first rule applies to it.
This .bar element follows the the previous .bar element, so the second rule applies.
This .bar element follows the the previous .bar element, which itself follwed a .bar element before that—so the third rule applies to it.
What happens if we put in a fourth .bar element? The third rule applies to it as well.