问题
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?
回答1:
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
回答2:
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 :)
回答3:
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.
来源:https://stackoverflow.com/questions/52983769/can-i-check-parent-element-has-specific-class-in-sass