Search code examples
csscss-selectorspseudo-class

Applying CSS3 to pseudo-class first-child


I have markup that goes something like this

<div class='wrap'>
<div class='container'>
Body Container content
</div>

<div class='container'>
Footer Container content
</div>
</div> 

I want to display a header containing, amongst other things, a logo above the first, body, container. This I accomplished by defining

.container::before
{
 background-image(url(path/to/image.jpg);
 background-size:cover;
 content:'';
}

The above works. The problem is that the logo ends up not onlyu above the body content but also above the footer content which is not quite the desired result. I have played around with various combinations of

.container::before:nth-of-child(1)
{

}

.container:nth-of-child(1)::before
{

}

but I haven't quite found the right syntax to target the ::before pseudo element for the first .container instance. I hope that someone here will be able to tell me how it should be done.

If the worst comes to the worst I can do it with a spot of jQuery but I would like to avoid that.


Solution

  • OK so I'll add another answer because it doesn't appear that anyone has solved all of your issues.

    First, there is a typo in your css: background-image(url(path/to/image.jpg) is missing the closing paren.

    To do what you want, however, there is a simple css selector :). In your example, you try nth-to-child(), but the correct syntax for what you want is nth-child(). Look below for two options, with a working demo.

    .container:first-child:before
    {
      display: block;
      content: "Before Element";
      /* other styling that you choose*/
    }
    
    /* the following selector will also work 
    .container:nth-child(1):before
    {
      display: block;
      content: "Before Element";
    }
    */
    <div class='wrap'>
      <div class='container'>
        Body Container content
      </div>
    
      <div class='container'>
        Footer Container content
      </div>
    </div>

    Note that the display: block; part is so that the before content appears on it's own line, since :before elements by default are display: inline-block;.