Hey everyone👋
When we want to create our web pages we use HTML.It describes the structure of a web page and consists of a series of elements.
Css is a stylesheet language used to describes how elements should be rendered on screen, on paper etc.
We can use of & nesting selector to set style for our elements.
There are different ways to use of it, such as:
- Set style for whole document The & nesting selector set style for all of elements in document.(when we didn't use of class name before or after that). For example:
&{
font-size:16px;
color:blue;
}
2.Set style for parent and child elements
When we want to set style for the below example:
<p class="parent">
This is a
<span class="child">
simple example
</span>
</p>
Maybe we use this syntax:
.parent{
color:black;
font-size:18px;
}
.parent .child{
color:white;
font-weight:800;
}
but with uses nested css styling, we write:
.parent{
color:black;
font-size:18px;
& .child{
color:white;
font-weight:800;
}
}
Note:
Whitespace is very important in this syntax.
If we set whitespace between & and .child(& .child)it sets styles for all child elements with child class name but when we remove whitespace(&.child)it means set styles for the element with both class name, parent and child, For example:
<p class="parent child">
This is a
<span>simple example</span>
</p>
In addition to using personal classes we can use & with pseudo-class and compound selectors, like this:
.parent{
color:black;
font-size:18px;
&:hover{
color:white;
font-weight:800;
}
}
Till now we've added & at the begining of the class name, that's while we can add it after the class name, for example:
.parent{
color:black;
font-size:18px;
.child &{
color:white;
font-weight:800;
}
}
It will compiled:
.parent{
color:black;
font-size:18px;
}
.child .parent{
color:white;
font-weight:800;
}
Note
We can add multi & in this syntax
.parent{
color:black;
font-size:18px;
.child & & &{
color:white;
font-weight:800;
}
}
It will compiled:
.parent{
color:black;
font-size:18px;
}
.child .parent .parent .parent{
color:white;
font-weight:800;
}
Conclusion
All of the examples produce the same output.Some of them are normal css styles that we usually use in our projects and the other one uses the & nesting selector.
Top comments (1)
You can just write this as
The
&
is only needed when you don't want to "add" something to the outer selector, like selectingsection.important
inside of asection
block you need to use&.important