Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check parent element has specific class in sass?

I want to assign value conditionally if parent element has a specific class. Exp:

HTML

<div class="parent">
    <div class="child">Some Text</div>
</div>

CSS

.child {
    font-size: 16px;
}

but if parent element has a class named "big"

HTML

<div class="parent big">
    <div class="child">Some Text</div>
</div>

I want to change value as follows

CSS

.child {
    font-size: 20px;
}

For example as follows:

.child {
  font-size: parent.hasClass('big') ? 20px : 16px;
}

How can I do that in SASS?

like image 585
midstack Avatar asked Oct 25 '18 07:10

midstack


People also ask

How do you target a parent element in Sass?

sass Nesting The parent selector (&)Create a new selector that requires both the parent selector and another on the same element by placing the new selector directly after a parent selector. Have the parent appear after a nested selector in the compiled CSS by placing the parent selector after the nested selector.

Is there a Sass parent selector?

The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.


2 Answers

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
like image 178
Justinas Avatar answered Oct 22 '22 22:10

Justinas


It's impossible using pure CSS (the whole idea is cascading). But there might be a way using SASS. Check this out:

http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand

EDIT: Another option would be using JavaScript, like Jpegzilla suggested.

like image 43
Dima Shivrin Avatar answered Oct 22 '22 22:10

Dima Shivrin