CSS Structural Pseudo-Classes

Structural pseudo-classes allow the selection of elements on the basis of the structure of the entire HTML document, which includes the position of each element and the number of times an element appears in the document.

A browser treats an HTML document as a tree of nodes, with elements and their child elements serving as nodes.

Structural pseudo-classes allow you to select these nodes and calculate the position of a child node in the node list of a parent node or element.

CSS Structural Pseudo-Classes Lists

Here is the list of structural pseudo-classes available in CSS:

CSS structural pseudo-class example

Consider the following code as an example demonstrating the structural pseudo-classes in CSS. I used comments to explain the main portion of the CSS codes.

<!DOCTYPE html>
<html>
<head>
   <style>
      /* Apply style to the first child element of the unordered list */
      ul li:first-child {
         background-color: lightblue;
      }

      /* Apply style to the second child element of the ordered list */
      ol li:nth-child(2) {
         background-color: lightgreen;
      }

      /* Apply style to every even child element of the table */
      table tr:nth-child(even) {
         background-color: lightgray;
      }

      /* Apply style to every odd child element of the definition list */
      dl dt:nth-child(odd) {
         font-weight: bold;
      }
   </style>
</head>
<body>

   <h1>Structural Pseudo-classes Example</h1>
   
   <ul>
      <li>First item</li>
      <li>Second item</li>
      <li>Third item</li>
      <li>Fourth item</li>
   </ul>
   
   <ol>
      <li>First item</li>
      <li>Second item</li>
      <li>Third item</li>
      <li>Fourth item</li>
   </ol>
   
   <table>
      <tr>
         <th>Name</th>
         <th>Age</th>
         <th>Gender</th>
      </tr>
      <tr>
         <td>William</td>
         <td>31</td>
         <td>Male</td>
      </tr>
      <tr>
         <td>Edwin</td>
         <td>30</td>
         <td>Male</td>
      </tr>
      <tr>
         <td>Susan</td>
         <td>23</td>
         <td>Female</td>
      </tr>
      <tr>
         <td>Lucas</td>
         <td>27</td>
         <td>Male</td>
      </tr>
   </table>
   
   <dl>
      <dt>Term 1</dt>
      <dd>Definition 1</dd>
      <dt>Term 2</dt>
      <dd>Definition 2</dd>
      <dt>Term 3</dt>
      <dd>Definition 3</dd>
      <dt>Term 4</dt>
      <dd>Definition 4</dd>
   </dl>
   
</body>
</html>

The snapshot given below shows the exact output that the above example produces.

css structural pseudo class example code

In this example, I am using the following four structural pseudo-classes to style different elements on the page:

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!