Can I check parent element has specific class in sass?

Viewed 36744

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?

3 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

There are no parent selectors in CSS. What you can do is setting your font-size on your parent class and let the children inherit that.

.parent {
    font-size: 16px;

    &.big {
        font-size: 20px;
    }
}

.child {
    font-size: inherit;
}

Or you can use CSS variables (if you don't need to worry about IE too much)

--font-size: 16px;

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

.parent {
    font-size: var(--font-size);
}

.child {
    font-size: inherit;
}

Hope that helps :)

Related