Search code examples
csscss-selectorspseudo-class

SCSS: pseudo-class :first-of-type affects all types


I would like to ask for your help regarding :first-of-type pseudo-class. Please, can you check the example of simplified code bellow i'm using - :first-of-type affects all types or nothing.

HTML:

<div id='nav'>
  <div class='row'> 

    <div class='cell'>
      <strong>Subject 1</strong>
      <ul>
        <li>item 1</li>
      </ul>
    </div>

    <div class='cell'>
      <strong>Subject 2</strong>
      <ul>
        <li>item 1</li>
      </ul>
    </div>  

  </div>
</div>

SCSS:

#nav{
  @extend %filter_full_size;

  strong{
    color: $color_blue;
    width: 100%;
    display: inline-block;
    position: relative;
    height: 3em;
    line-height: 3em;

    &:first-of-type{
      &:after{
        content: '';
        display: inline-block;
        position: absolute;
        width: 200%;
        height: 1px;
        background-color: $color_blue;
        bottom: 0;
        left: 0;
      }
    }
  }
}
      

I also tried to use :first-of-type for parent element with class 'cell' but it didn't work at all.

#nav{
  @extend %filter_full_size;
  
  .cell{
    strong{
      ......
    }

  &:first-of-type{ 
    strong{ 
      &:after{
        ......
      }
    }
  }
}

Thanks for your help. P.


Solution

  • Your first attempt picked up every strong element since they were all the first children of their respective parent elements.

    I couldn't at first glance see anything wrong with your second attempt, where you had selected the strong element that was a child of the first .cell element. However, we haven't seen the full code so maybe there is something wrong in that?

    I 'translated' the SCSS to CSS to check and this is the result I saw: enter image description here

    If this is what you wanted here is the snippet:

    #nav .cell strong{
        color: blue;
        width: 100%;
        display: inline-block;
        position: relative;
        height: 3em;
        line-height: 3em;
    }
    
     #nav .cell:first-of-type strong::after{
            content: '';
            display: inline-block;
            position: absolute;
            width: 200%;
            height: 1px;
            background-color: blue;
            bottom: 0;
            left: 0;
          }
    <div id='nav'>
      <div class='row'> 
    
        <div class='cell'>
          <strong>Subject 1</strong>
          <ul>
            <li>item 1</li>
          </ul>
        </div>
    
        <div class='cell'>
          <strong>Subject 2</strong>
          <ul>
            <li>item 1</li>
          </ul>
        </div>  
    
      </div>
    </div>