css and/or SASS + (sibling) selector upwards

Sass

Sass Problem Overview


In CSS there is no way to select a sibling with plus if the sibling is above in the output, a preceding element in the html.

For example

<div class="first">
<div class="second">

.second + .first { style applied to div.first}

Is there anyway to do this in SASS/SCSS?

Sass Solutions


Solution 1 - Sass

SASS support all CSS3 selectors. Sibling + is one of them. But it does not bring some extra features. It means you can do

first {
  + second { 
     font-size: smaller;
  }
}

But you can't impact a parent with it ...

Ps : it seems to be a features of CSS4 :)

Solution 2 - Sass

I know the feeling, this is really annoying. I found a quick way of doing it tho.

HTML

<div class="mainmenu">
  <div class="subnav">
    <ul>
      <li>Whatever</li>
    </ul>
  </div>
</div>

SCSS

CSS is pointed towards to first child of div "mainmenu" with the > class "subnav"

 .mainmenu{
      & > .subnav{
         // Child Selector SCSS HERE
      }
  }

@thgaskell, you have proved me wrong :) My code works fine and I lost 6KB of my Minified code! I have updated the code as how the comment below was informed.

Solution 3 - Sass

May or may not be suitable for your needs but you can use the general sibling selector in Sass/CSS. This will select all elements on the same node level (not explicitly before but still handy):

.second {
   .first ~ & {
       /* styles to be applied to .second if a .first exists at the same node level */   
   }
}

Solution 4 - Sass

I ended up using Jquery. gets the job done :) (sorry i dont have the example code anymore as i went another route, but its quite simple, something like 'if child has class then add class to this'. :)

Solution 5 - Sass

div { & + & { margin-left: 15px; background: firebrick;}}

try it it's work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpetergusView Question on Stackoverflow
Solution 1 - SassXavierView Answer on Stackoverflow
Solution 2 - SassNeilView Answer on Stackoverflow
Solution 3 - SassBen FrainView Answer on Stackoverflow
Solution 4 - SasspetergusView Answer on Stackoverflow
Solution 5 - SassUmair Zulfiqar KhanzadaView Answer on Stackoverflow