CSS can be cumbersome to read. It becomes easily very difficult to figure out which is the parent and which is the child. Also, which is the immediate parent and which is the immediate styles. Hence, concept of nesting was introduced, initially in CSS pre-processors such as SASS and now in native CSS.
CSS now has a &
nesting selector support built in. This provides a familiar syntax to most of the CSS pre-processors to nest the CSS selectors.
CSS Nesting selector basics
To nest CSS, it isn't necessary to use the nesting operator. It can be done without that as well.
.parent {
/* Parent's CSS Code */
.child {
/* Child's code */
}
}
This will evaluate to:
.parent {
/* Parent's CSS Code */
}
.parent .child {
/* Child's CSS Code */
}
But then why do we require the &
nesting operator?
Well, we can also nest the pseudo-selectors and we might need to mention classes which require them to be written without the whitespace. In these situations, we are mandated to use the nesting operator. Let's see an example.
.parent {
/* Parent's code */
:hover {
/* Hover state code */
}
}
Intended functionality:
.parent {
/* Parent's code */
}
.parent:hover {
/* Hover state code */
}
But what we actually get:
.parent {
/* Parent's code */
}
.parent *:hover {
/* Hover state code which gets applied to all the child element's hover states */
}
Which is not the desired functionality.
Also note that currently (at the time of writing of this article) browsers except firefox do not support type selectors (tags) to be nested without the nesting operator.
Appending the CSS nesting operator
Nesting operator can be appended to the right as well to reverse the effect. With the &
at the left side of the operator, it was giving .parent .child
. But if we append it, we will get .child .parent
which reverses the effect. Now here we are referring to the element with .parent class which lies inside the element with .child
class.
This can be done multiple times as well. Appending the nesting operator or pre-pending the nesting operator multiple times will duplicate the selector there.
Here is an example to illustrate this:
Well, with CSS nesting operator, it is now a better choice to use it rather than repeating the classes again and again just to point to their children. Also, if you are using CSS pre-processors such as SASS (or SCSS) just due to the variables and nesting, then you should reconsider your choice as CSS has support for both nesting as well as variables.
If you came this long, you must have liked the post. I highly recommend you to follow to never miss learning new and unknown things in the domain of web development. You can always unfollow if you don't like it in the future.
Let's get connected on linkedin: https://www.linkedin.com/in/sahil2004/
I post such amazing content there as well.
Top comments (0)