Grow your CSS skills. Land your dream job.

:first-child is not working for me…

  • # December 3, 2012 at 3:27 pm

    Hello.

    I would like to understand why the following can’t be applied to h2:

    item-page h2:first-child a{
    text-decoration:none;
    text-align:left;
    line-height:27px;
    font-size:28px;
    margin-bottom:10px;
    font-weight:bolder;
    color:#000;
    background:red;

    }

    I can’t understand why h2 is not getting the styles.

    Thanks in advanced for your time and help.

    # December 3, 2012 at 3:32 pm

    Because the `h2` is *not* the first child, the `h1` is the first child element of `.item-page`. You’re probably looking for `h2:first-of-type` but that is not supported by IE7 & IE8.

    # December 3, 2012 at 3:33 pm

    First, you need a period in front of your class (.item-page). Next, you need to move the :first-child behind the ‘a’. So it will look like this instead:

    .item-page h2 a:first-child

    # December 3, 2012 at 3:34 pm

    First item-page should be `.item-page`, but assuming that one was just a copy-paste typo. Well h1 is the first-child of item-page, rather than h2. If you’d want the h2 to get that style, maybe you would be looking for `:first-of-type` selector.

    # December 3, 2012 at 3:55 pm

    There’s a few ways you could get around this using descendant, sibling or adjacent selectors.

    Is the format of .item-page always going to be the same pattern?

    # December 3, 2012 at 3:56 pm

    Yes, the missing dot was a copy/paste typo.

    :first-of-type did the work.

    I thought that :first-child meant the first h2 in .item-page …

    Thanks a lot for clarifying that.

    # December 3, 2012 at 5:17 pm

    @landysaccount – :first-of-type is indeed handy but I’d recommend against using it for core styling at this point due to browser support. It might be better to use alternative (sneakier) selectors instead to get around that and ensure wide support.

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

You must be logged in to reply to this topic.

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