Grow your CSS skills. Land your dream job.

Target with CSS all h2 EXCEPT first one on a page

  • # February 28, 2011 at 9:13 am

    Is it possible to Target with CSS all h2 on a wordpress site EXCEPT first one on a page?

    I would like to add some kind of styling to the h2 title tags on a wordpress page to visually separate the posts, but adding margin or padding to the first one on the page moves the top of page out of alignment.

    Any ideas?

    Thank you,
    Charlie

    # February 28, 2011 at 9:24 am

    You can if they’re siblings:

    h2 ~ h2{border-bottom: 3px solid red;}

    I don’t think you will be able to do this (If they’re not siblings) as CSS cascades.

    # February 28, 2011 at 11:58 am

    You could try :nth-of-type(N)

    Read about it here

    H2:nth-of-type(2) {…your styling…}

    # February 28, 2011 at 12:11 pm

    That could work. I’ll have to limit the total number of posts to display. But that shouldn’t be a problem.

    Thank you!

    # February 28, 2011 at 1:16 pm

    What is the proper way to designate the h2’s you want to style…

    :nth-of-type(2-10) would be the 2nd through 10th h2?
    or (2-*) would be the 2nd through all present h2’s?

    or something else?

    # February 28, 2011 at 1:23 pm

    Use:
    :nth-of-type(n+2)

    n=0, then it targets the second.
    n=1, then it targets the third.
    n=2, then it targets the forth.
    etc.

    I think you guys were over thinking this.

    # February 28, 2011 at 1:34 pm

    You don’t need to designate a range?

    # February 28, 2011 at 1:38 pm

    You will need to target all the h2s then override that style for the first h2

    h2 { color: #fff; }

    h2:nth-of-type(1) { color: #333; }

    /*only the first h2 will be dark grey, the others will be white */

    or you could again target all the h2s and override using a descendant selector or child selector. Some code would help us show you the best route.

    # February 28, 2011 at 1:43 pm

    @charlie, why would you need to designate range? :nth-of-type isn’t even built for ranges, you can only plug in basic equations. Also, your :nth-of-type(2-10) wouldn’t be “The second through tenth” it would be “Two minus ten”.

    Just do this:

    h2 { color: #fff; }

    h2:nth-of-type(n+2) { color: #333; }

    Or whatever those styles should be. The first style would target all H2’s and the second will target all H2’s other than the first.

    # February 28, 2011 at 2:57 pm

    Ahhhh.

    Thank you.

    # February 28, 2011 at 4:26 pm

    Yes, :nth-child() takes “n”, sets it to 0, solves the equation, and then applies the style to the element of that number in order. And then it sets “n” to 1, solves the equation… etc etc. and it does that over and over again so it applies to all

Viewing 11 posts - 1 through 11 (of 11 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".