Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a style to both parent and child in SCSS

Tags:

css

sass

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.

like image 894
Simona Adriani Avatar asked Feb 22 '17 13:02

Simona Adriani


People also ask

How do I apply CSS to child element based on parent?

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.

Is there a SCSS 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.

How do I traverse from parent to child in CSS?

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.


1 Answers

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.
    }
  }
}
like image 113
numbers1311407 Avatar answered Oct 17 '22 02:10

numbers1311407