How to Select a Class within a Class in CSS?

To select a class within a class, you can use the descendant selector. The descendant selector allows you to select the descendants of an element.

For example, if there are two classes outer and inner and the inner class is within the outer class. So, if we want to select the inner class element, we have to give a white space between the outer and the inner class i.e. .outer .inner.

Let’s say we have a div element with class="outer" and it has two child paragraphs, one with class inner and another without any class:

<div class="outer">
   <p class="inner">Paragraph with inner class</p>
   <p>Paragraph with no class</p>

Now, to select the inner class element, we just need to put a white space between the outer and inner class i.e. .outer .inner.

Something like this:

/*Select inner class paragraph*/
.outer .inner{
    background-color: yellow;

This will be the output after applying the above styles:

Select a class within a class in CSS

Similarly, if there are more nested classes, you just need to separate them with a white space and you can select any nested class element you want.

Something like this:

.class1 .class2 .class3 .class4{
    /*styles goes here*/

Thanks for reading.


  • 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.