How to select first 2
  • elements using css
  • 后端 未结 4 1422
    悲&欢浪女
    悲&欢浪女 2020-12-13 08:26

    Hi i want to apply css for first 2 elements (one,two) that are adjacent to first

    element.

    相关标签:
    4条回答
    • 2020-12-13 08:46

      Like others already mentioned, the straightforward answer would be li:nth-child(-n+2) { ... }.

      I don't know about you, but when I first learn this -n+2 part, my reaction was "what? is this a typo?". So, for those who like to know a little explanation rather than just copy-and-paste the counter-intuitive magic, here I include a link to a wonderful blog post by Sara Cope explaining the -n+2 part:

      The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n, plus the positive number of elements you want to select. For example, li:nth-child(-n+2) will select the first 2 li elements.

      Such explanation is even missing in the w3cshool for nth-child.

      0 讨论(0)
    • 2020-12-13 08:52

      For first 2 li elements inside ul p try:

      .one ul li:nth-child(-n+3){
          // your style
      }
      

      See on jsfiddle

      And as other mates mentioned: you have invalid markup.

      If you removed p element, try:

      .one ul li:nth-child(-n+2){
          // your style
      }
      

      See on jsfiddle

      Update: My suggestion is to use another ul instead of p: So you have valid markup and same result:

      HTML

      <div class="one">
          <ul>
              <li>0</li>
              <li>
                  <ul>
                      <li>One</li>
                      <li>Two</li>
                      <li>3</li>
                  </ul>
              <li>
              <li>Four</li>
              <li>Five</li>
          </ul>
      </div>
      

      CSS:

      .one ul {
          padding: 0;
          list-style-type: none;
      }
      .one ul ul li:nth-child(-n+2){
          // your style
      }
      

      Updated jsfiddle

      Note: As your last comment, If you have only 2 special li element, Why not define a class name simply... <li class="bold"> Do it simple

      ul li.bold {
          // your style
      }
      
      0 讨论(0)
    • 2020-12-13 08:56

      This should be compatible with IE8 (uses CSS 2.1 selectors only):

      li:first-child, li:first-child+li {
          color: blue;
      }
      
      0 讨论(0)
    • 2020-12-13 09:06

      First three elements you can select with e.g.

      ul li:nth-of-type(-n+3) {
      
      }
      

      But like others mentioned, your markup is invalid and you should definitely correct it.

      0 讨论(0)
    提交回复
    热议问题