How to Check Parent Element Has Specific Class in Sass

Can I check parent element has specific class in sass?

Simply create two rules:

.child {font-size: 16px;}
.big .child {font-size: 20px;}

In SASS it would be

.child
font-size: 16px

.big &
font-size: 20px

Sass selector that checks if a class is on any ancestor

Yes it is. You can use & like this:

.seed {
.tree & {
/** Wow! I'm seed in tree! */
color: red;
}
}

You can read more about Parent Selector in Sass documentation.

Sass - if class has this parent

According to this GitHub issue, you can use the following as of SASS v3.3.0:

.foo {
color: blue;
@at-root {
p#{&} {
background: yellow;
}
span#{&} {
background: red;
}
}
}

Which outputs:

.foo {
color: blue;
}
p.foo {
background: yellow;
}
span.foo {
background: red;
}

How to select parent using SCSS

Use parent selector & after the class, something like this:

.username {
color: red;

.mobile & {
font-weight: bold
}

.desktop & {
font-weight: normal
}
}

Here is a demo

SS

Note: don't need to repeat the color: 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