DEV Community

pawan deore
pawan deore

Posted on • Updated on

Advanced Guide for CSS Selectors

Okay so till now we generally used common CSS selectors like class, id, universal and element name

in example that will be indicated like

class -> .
id -> #
tagName -> tagName
universal -> *
attribute -> [attribute]

Okay so today we will review some other selectors


1] Descendant combinator

this thing is pretty dangerous i guess 😂 reason is if we assign some styles with this rule it will be big pain in a** let me explain

div p {
color: red;
}

it will apply styles to all p tag whether it is just below div or at any other level below div, sometimes it helps sometimes becomes trouble. meaning it will be applicable to

div > h2 > p
div > p



2] Child combinator

this one is solution for the 1st one we saw its classes will be applicable to the exact child of the parent not to the every element under that parent.

example

div > p {
color: red;
}

now color red only be applied for the elements which are direct child of div not to the every p element.



3] General sibling combinator

well this rule is useful in some critical times we struggle to style to next all elements below specific element, syntax is

div ~ p {
color: red;
}

this will apply color red to all p tags which are next to div tags



4] Adjacent sibling combinator

well this rule is exactly like the previous but only difference here is styles will be applied ONLY to the next element i.e. adjacent element not to all elements below it.

example syntax

div + p {
color: red;
}

and that's it for this post i guess. if you love this post then follow me for more posts.

Top comments (0)