Sass: Selecting The Parent Element with Multiple Nested Selectors

How to target a child element of a multiple parent selector in SASS

If you really want to do this you can try something like this:

.overlay {
height: 400px;
.categoryHero & {
height: 200px;
}
}

The trailing ampersand will select the parent of .overlay here, which in this example is categoryHero. If categoryHero isn't the parent, .overlay will still have a height of 400px. That being said, if you've got more than just two possible parents for overlay, then I can't see a way around having multiple trees in your sass.

How to select nth-child in SASS within a nested selectors

If you need to group the selectors in this way - I recommend using the @at-root directive.

The @at-root directive causes one or more rules to be emitted at the
root of the document, rather than being nested beneath their parent
selectors.

.group-left {
.clip-item & {
padding: 0;
}
@at-root .clip-item &:nth-child(2n+1) {
background: blue;
}
@at-root .clip-item &:nth-child(2n+2) {
background: gray;
}
}

.group-right {
.clip-item & {
padding: 0;
}
@at-root .clip-item &:nth-child(2n+1) {
background: blue;
}
@at-root .clip-item &:nth-child(2n+2) {
background: gray;
}
}

Codepen demo (View compiled CSS)

Also, this CSS-tricks post may help:

The & doesn't allow you to selectively traverse up your nested
selector tree to a certain place and only use a small portion of the
compiled parent selector that you want to use.


By the way:

Even though it's working, I don't think it's the right way

Well actually, your SCSS is not currently producing the requested CSS.

How to target the parent class from nested classes in SASS

You could use parent selector and invert your nesting in sass

.group-left {
.wrapper & {
background-color: blue;
}
.wrapper-child:nth-child(2n+2) & {
background: red;
}
}

Select parent selector in SASS/SCSS

Either you write both the selectors with the full classname (without using &) or you could save a reference to the .message class and use it in the nested selector

.message {

display: block;
width: 300px;
border-radius: 5px;
border: 2px solid #000;
padding: 10px;

$this: &; /* reference to the .message class */

&__title {
font-size: 18px;
line-height: 1;
color: #000;
margin-bottom: 10px;
}

&__content {
font-size: 15px;
color: #000;
}

&--success {
border-color: #3f9442;

/* use the reference stored */

#{$this}__title {
color: #3f9442;
}

#{$this}__content {
color: #3f9442;
}
}
}


Related Topics



Leave a reply



Submit