nth-child Selector

nth-child Selector
CSS nth-child Selector reference
The CSS nth-child structural pseudo-class selector ( X:nth-child() { } ) is used to target and style child elements according to their position in their specified parent element. Define the numeric value for position in between the parenthesis. I produced a video tutorial about using this selector to alternate styles if you want to know a bit more about it, click here to view that video.
CSS CODE EXAMPLE
<!DOCTYPE html>
<style type="text/css">
div p:nth-child(2) {
    color:#F00;
}
</style>
<div>
  <p>Paragraph content...</p>
  <p>Paragraph content...</p>
  <p>Paragraph content...</p>
</div>
 
Paragraph content...
Paragraph content...
Paragraph content...
Using numeric values with "n", "+" and "-" will allow you to set style logic for many selection methods. You can use the keywords of "odd" and "even" for alternating styles every other element as shown in the video tutorial that I linked to above.
CSS CODE EXAMPLE
<style type="text/css">
.myTable { width:100%; border-collapse:collapse; }
.myTable td { padding:8px; border:#999 1px solid; }

.myTable tr:nth-child(2n+0) {
    background: #B9DCFF;
}
.myTable tr:nth-child(2n+1) {
    background: #FFE7AE;
}
</style>
<table class="myTable">
  <tr>
    <td>Row 1 content</td>
  </tr>
  <tr>
    <td>Row 2 content</td>
  </tr>
  <tr>
    <td>Row 3 content</td>
  </tr>
  <tr>
    <td>Row 4 content</td>
  </tr>
</table>
 
Row 1 content
Row 2 content
Row 3 content
Row 4 content

0 Response to "nth-child Selector"

Post a Comment