Search code examples
htmlcsscss-selectorspseudo-elementpseudo-class

CSS path to element using multiple pseudo-classes/elements not working


I was wondering if its possible to target an element by stacking pseudo classes.

I tried this:

#advertise .row:first-of-type .one-third:nth-of-type(2) .contentwrap {
  font-size:16px;
}

but it only works if us the ID for the rows [#one or #two] in place of the .row:first-of-type/.row:last-of-type

Is this because i cant target elements using multiple pseudo's or am im just doing something silly and not realising?

Here is the HTML:

<div id="advertise">
    <h1 class="maintitle"></h1>
    <h2 class="maintitle-sub"></h2>

    <div class="contentwrap">
        <p></p>
    </div>

    <div class="row" id="one">
        <div class="one-third first shadow">
            <h1 class="header"></h1>
            <div class="contentwrap">                
                <p></p>
            </div>
        </div>
        <div class="one-third shadow">
            <h1 class="header"></h1>
            <div class="contentwrap">
                <p></p>
            </div>
        </div>
        <div class="one-third shadow">
            <h1 class="header"></h1>
            <div class="contentwrap">
                <p></p>
            </div>
        </div>
    </div>

    <div class="row" id="two">
        <div class="one-third first shadow">
            <h1 class="header"></h1>
            <div class="contentwrap">                
                <p></p>
            </div>
         </div>
         <div class="one-third shadow">
            <h1 class="header"></h1>
            <div class="contentwrap">
                <p></p>
            </div>
        </div>
        <div class="one-third shadow">
            <h1 class="header"></h1>
            <div class="contentwrap">
                <p></p>
            </div>
        </div>
    </div>
</div>

Solution

  • The :first-of-type selector selects the first instance of a specific type of element (e.g. <div>). Here, your first .row element is the second <div> element, and thus your :first-of-type selector does not select it.

    Instead, you can use:

    #advertise .row:nth-of-type(2) .one-third:nth-of-type(2) .contentwrap {
      font-size:16px;
    }
    

    But as it already has an id attribute (which should be unique to that element), you may as well stick with:

    #advertise #one .one-third:nth-of-type(2) .contentwrap {
      font-size:16px;
    }