Style every third element?

前端 未结 8 1598
小蘑菇
小蘑菇 2020-12-15 05:11

How can I style every third element with plain CSS.

I have seen questions like this, but they involve javascript. I want a plain CSS solution. I know I can use

相关标签:
8条回答
  • 2020-12-15 05:49

    This is possible with pure CSS. No javascript needed.

    Use the nth-child selector.1

    section > div:nth-child(3n+1) {
        background:red;
    }
    

    Where '1' is where the style starts, and 3 indicates that it should style every third element. It is explained much better here.

    jsFiddle demo here.


    1Note - as other people have mentioned this is not fully supported by IE8 and down.

    0 讨论(0)
  • 2020-12-15 05:51

    Pure CSS, No Javascript, with IE7/8 Support

    Requires Change of HTML, or...

    You must either explicitly set some class on the elements you want changed in your HTML, whether dynamically through server side script counting, or manually by hard coding.

    Demo Fiddle

    HTML

    <section>
      <div class="someclass explicitClass"></div>
      <div id="someId"></div>
      <div class="someotherclass"></div>
      <div id="someotherId" class="explicitClass"></div>
      <div class="someclass"></div>
      <div id="someId"></div>
      <div class="someotherclass explicitClass"></div>   
    </section>
    

    CSS

    .explicitClass {
        your-property-to-change: your-value-desired;
    }
    

    ... Requires Extensive CSS Markup

    Or you must generate CSS that is "counting" for you in a bulky way. As Indy noted in his answer (not sure why he stated adjacent sibling is "not available by default in IE8 or below," as that is incorrect), this could be handled through a CSS preprocessor, but even then, you really don't want to go this route unless you have a very limited number of elements, probably no more than what you posted for your example. If there were hundreds of elements, this is not practical. This solution requires no change in your HTML.

    DEMO Fiddle

    CSS

    section div:first-child,
    section div:first-child + div + div + div,
    section div:first-child + div + div + div + div + div + div {
        your-property-to-change: your-value-desired;
    }
    

    Ultimately, I Agree with JoshC and Indy

    I've offered the above answers just to show what you must do if you really want what you say you want. If it were me, unless it was absolutely vital to have these change of styles on every third element (so javascript turned off is fatal to the whole scheme; and even that could be worked around to restyle for non-javascript), I would use JoshC's answer as your CSS, and then use some form of javascript solution to make it backwards compatible (as Indy noted, or any other form of javascript solution).

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