Style every third element?

前端 未结 8 1621
小蘑菇
小蘑菇 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条回答
  •  Happy的楠姐
    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

    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).

提交回复
热议问题