Search code examples
csssassparent

How to add some style only for main parrent in SASS


I have this markup:

<ul> // w style: border-top: 2px solid #aaa; border-bottom: 1px solid #ccc;
  <li>
    <ul> // w style: border-bottom: 2px solid #aaa;
      <li>
      <li>
    </ul>
  </li>
</ul>

I need to add some style to the main parent and a touch of style that will be inherited for the same item within - as above. So i do this, but it is't work...

ul {
   border-top: 2px solid #aaa;

   & > {
     border-bottom: 1px solid #ccc;
   }
}

I know that I can duplicate tag and specify a different style for him inside, but in general is the possibility of such record/write? Thx for help.


Solution

  • I believe your use of the nested selector is wrong, it must be throwing errors from Sass. You have used the direct descendent selector > after the alias for the containing selector in this case the ul, so your compiled selector would look like ul > which is invalid.

    The selector should follow the pattern parent > child. You may be attempting ul > ul but the nested ul is not a direct descendent of the main ul rather it is a child of li.

    Your amended code:

    ul {
       border-top: 2px solid #aaa;
    
       & > li > & {
         border-bottom: 1px solid #ccc;
       }
    }
    

    But note this rule will also apply in the following situation too, so you should probably go for a class on the nested ul.

    HTML

    <ul> // w style: border-top: 2px solid #aaa; border-bottom: 1px solid #ccc;
      <li>
        <ul> // w style: border-bottom: 2px solid #aaa;
          <li>
            <ul> // Another list
              <li></li>
              <li></li>
            </ul>
          <li>
        </ul>
      </li>
    </ul>
    

    So this would be better

    <ul> // w style: border-top: 2px solid #aaa; border-bottom: 1px solid #ccc;
      <li>
        <ul class='sub-list'> // w style: border-bottom: 2px solid #aaa;
          <li>
          <li>
        </ul>
      </li>
    </ul>
    

    with the following css/scss

    ul {
      border-top: 2px solid #aaa;
    }
    
    .sub-list { /* Will inherit the above if used on a ul */
       border-bottom: 1px solid #ccc;
    }