[CSS] DOM Hierarchy Pseudo Classes :first-child :last-child :nth-child (demystified)

DOM hierarchy pseudo-classes allow you to style specific elements based on where they fall in the hierarchy and what type of elements they are. You can also use :nth-child to target custom element patterns, like every other element.

 

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>GistRun</title>
  <link rel="stylesheet" href="styles.css">
      <style>
        ul {
            list-style: none;
            margin: 0;
            padding: 0;
        }

        li {
            padding: 5px;
        }

        /*    li:first-child {
                background-color: rgb(225, 231, 252);
            }
            li:last-child {
                background-color: rgb(225, 231, 252);
            }
            li:nth-child(2) {
              background-color: rgb(225, 0, 252);
            }*/
        /* The even child*/
        /*li:nth-child(2n) {
            background-color: gold ;
        }*/

        /* The odd child*/
        /*li:nth-child(2n+1) {
            background-color: darkred;
        }*/

        /* First 4 children */
        li:nth-child(-n+4) {
            background-color: cadetblue;
        }

        /* Expect first three children*/
        li:nth-child(n+4) {
            background-color: lightgoldenrodyellow;
        }

        /* Other psuedo classes:
        * :nth-last-child
        * :only-child
        * :only-of-type
        * :last-of-type
        * :nth-of-type(an+b)
        * :nth-last-of-type(an+b)
        */</style>
</head>
<body>
  <ul>
    <li><a href="#" target="_blank">target=_blank</a></li>
    <li><a href="#" target="someFrame">target=someFrame</a></li>
    <li><a href="#" rel="link-blog">rel=link-blog</a></li>
    <li><a href="#" rel="linkproducts">rel=linkproducts</a></li>
    <li><a href="#" rel="link about">rel=link about</a></li>
    <li><a href="#" rel="link-about" title="special">rel=link-about title=special </a></li>
    <li><a href="#" rel="link-other" title="special">rel=link-other title=special </a></li>
    <li><a href="#" rel="this item available now">rel=this item available now</a></li>
    <li><a href="#" rel="product-200-available-now">rel=product-200-available-now</a></li>
    <li><a href="#" rel="linkproductavailable300">rel=linkproductavailable300</a>
    <li><a href="#" rel="sale-product-400">rel=sale-product-400</a></li>
    <li><a href="#" rel="sale">rel=sale</a></li>
    <li><a href="#" rel="product-500-discontinued">rel=product-500-discontinued</a></li>
    <li><a href="#" rel="product600discontinued">rel=product600discontinued</a></li>
    <li><a href="#" rel="discontinued">rel=discontinued</a></li>
</ul>
  <script src="script.js"></script>
</body>
</html>

 

 

posted @ 2016-06-17 00:56  Zhentiw  阅读(261)  评论(0编辑  收藏  举报