[CSS] Selectors (2) – Tree Selectors

Elements in HTML are constructed in a tree structor, from the root <html> element. CSS selectors can navigate elements in a tree.

 

1. Decendant Selector

element1 element2

The matched element can be any decendant element (a child, grandchild, etc…)

<head>
  <style type="text/css">
    body h1 { color:Blue; font-weight:bold; }
  </style>
</head>
<body>
  <header>
    <h1>Test Page</h1>
  </header>
</body>

 

2. Child Selector

element1 > element2

It is more restricted than a decendant selector, as only a child elment can be matched.

<head>
  <style type="text/css">
    header > h1 { color:Red; font-weight:bold; }
    body > h1 { color:Blue; font-weight:bold; }
  </style>
</head>
<body>
  <header>
    <h1>Test Page</h1>
  </header>
</body>

The title will be displayed in red not in blue.

 

3. General Sibling Selector

element1 ~ element2

The matched element can be any element , which has the same parent.

<head>
  <style type="text/css">
    h1 ~ h3 { color:Green; }
  </style>
</head>
<body>
  <header>
    <h1>Title</h1>
    <h3>Author</h3>
    <h2>SubTitle</h2>
    <h3>Comment</h3>
  </header>
</body>

Both <h3> elements are selected.

 

4. Adjacent Sibling Selector

element1 + element2

Only the following adjacent element is selected.

<head>
  <style type="text/css">
    h1 + h3 { color:Green; }
  </style>
</head>
<body>
  <header>
    <h1>Title</h1>
    <h3>Author</h3>
    <h2>SubTitle</h2>
    <h3>Comment&lt/h3>
  </header>
</body>

Among 2 <h3> element, only the first one that is next to <h1> is selected.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s