How to Select Nested Elements in CSS?

There are two easy ways that you can use to select nested elements in CSS. First, the descendant selector, and second the child selector.

The descendant selector selects all the elements that are inside a given element. To select all the nested elements using the descendant selector, we put a white space between the parent and its descendant.

For example, if you want to select all the paragraphs that are inside a div element, you have to use div p.

See this working example:

Example:

div p{
   background: yellow;
   padding: 5px;
}

Similarly, if you want to select all spans that are inside a paragraph which are again inside a div element, then you have to use div p span.

See this working example:

Example:

div p span{
   background: yellow;
   padding: 5px;
}

Method 2: Using child selector –

Another easy approach to select nested elements is using the child selector. To select all the nested elements using a child selector we put a > symbol between the parent and the child. For example, div > p, div > p > span, etc.

A child selector does also select nested elements like the descendant selector. But, it selects only those elements which are the direct children of a given element and not every element that is inside of it.

See this example for clarification:

Example:

div > p{
   background: yellow;
   padding: 5px;
}

Select nested classes:

You can not only use the descendant and the child selectors to select the nested elements with tag names but with the nested classes, ids, and attributes also.

See the following example where we are selecting every nested span that has class3:

Example:

.class1 .class2 .class3{
   background: yellow;
   padding: 5px;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.