skip to Main Content

css not work enter image description here
enter image description here

i hope the .a class first color will be red , but not work .

<style>
  .a:first-child {
    color: red;
  }
</style>

<body>
  <ul>
    <li>0</li>
    <li title="1" class="a">1</li>
    <li title="2" class="a">2</li>
    <li title="3" class="a">3</li>
    <li>4</li>
  </ul>
</body>

2

Answers


  1. Remove the first child and try running the code. That should work fine.

    Login or Signup to reply.
  2. :first-child pseudo-class only works when your element is the first child of its parent.

    Unfortunately, there’s no "elegant" way to do what you try to do, i.e. there’s no :first-of-class as of yet. See this answer for more details.

    So, a bit more code but this is probably the most "elegant" way to do it currently:

    <style>
      /* Color all "a" class elements with red */
      .a {
        color: red;
      }
      
      /* Make all "a" class elements with default color, except for the first one */
      .a ~ .a {
        color: inherit;
      }
    </style>
    
    <body>
      <ul>
        <li>0</li>
        <li title="1" class="a">1</li>
        <li title="2" class="a">2</li>
        <li title="3" class="a">3</li>
        <li>4</li>
      </ul>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search