Home > Net >  SCSS parent selector not works
SCSS parent selector not works

Time:09-22

I have a container and three parts in it. I want to make unvisible thirth part while addind class to the parent container. But my codes not works...

Here is the HTML code:

<section id="parts" class="two-parts">
    <div id="partOne">...</div>
    <div id="partTwo">...</div>
    <div id="partThree">...</div>
</section>

Here is the SCSS code:

#partThree{
    display: block;

    .two-parts &{
        display: none;
    }
}

I want to hide #partThree div, when #parts div has .two-parts class.

Guys! I found the problem. I checked the output of Scss to Css, and here is the Css output:

.two-parts body #parts #partThree {
  display: none;
}

It should be #parts.two-parts #partThree. But why is that goes to the top of all elements?

CodePudding user response:

As I have answered in your other post:

It looks like your code is wrapped by a body-tag and a #parts-tag. This means you need to change your code to this:

#partThree{
    display: block;
}

&.two-parts #partThree {
    display: none;
}

The & takes EVERYTHING before the current line. So if your final SCSS is:

body {
    #parts {
        #partThree {
            display: block;

            .two-parts & {
                display: none;
            }
        }
    }
}

Then the & will add .two-parts before everything else, and make it:

.two-parts body #parts #partThree {
    display: none;
}

CodePudding user response:

The easiest way to achieve what you need is by setting .two-parts and #partThree as siblings, and apply ~ css operator.

<style>
  #partThree {
    display: block;

  .two-parts ~ {
    display: none;
  }
}
<style>

<section id="parts">
    <div id="partOne">...</div>
    <div id="partTwo" class="two-parts">...</div>
    <div id="partThree">...</div>
</section>

this will only work if #partThree and .two-parts siblings and .two-parts comes before.

  • Related