I have this situation:
<div class="parent">
<a class="child"></a>
</div>
and I wanto to give width: 100% rule to both. Is there a better way in SCSS rather than writing:
.parent{
width: 100%;
.child{
width: 100%;
}
}
I am rather new to SCSS syntax, and so maybe it is a very simple question, but nowhere I can find a simple answer.
It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinator ( > ), which is placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.
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.
In a css selector if we need to traverse from parent to child we use > symbol. To get all the immediate children we have to specify * symbol after parent node in the css expression. So the customized css should be parent > *. So for a <ul class="toc chapter">, the css for immediate children shall be ul.
You target the current selector with &
, so you could write:
.parent {
&, .child {
width: 100%;
}
}
As a bonus, you also use &
as follows:
.parent {
&.mother {
// target elements classed `parent` AND `mother`
.grandparent & {
// target elements classed `parent` AND `mother` with a
// `grandparent` ancestor.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With