Basic CSS: How to Use Class Within Another Class

Want to apply a CSS style to a class within another class? In this tutorial, I'll show you everything you need to know to use CSS classes.

To nestle classes or any other selector in CSS, just separate the selector hierarchy with spaces. Example: .parent .child { /* CSS Properties */ }

Let's say you have the following code, and want to apply style only to <h1 class="post-title"> that is within <article class="blog-post">.

<article class="blog-post">
	<h1 class="post-title">Blog title</h1>
	<p>Article content</p>
</article>

Your CSS file will be like this:

.blog-post .post-title {
	/* CSS Properties */
	color: grey;
}

All h1's with "post-title" class that are within the "blog-post" class receive the CSS property. Even if they are nested inside other tags. While everything outside "blog-post", the rule will not apply.

For demonstration purposes, if we want to apply the same effect to all h1, independent of class:

.blog-post h1 {
	/* CSS Properties */
	color: grey;
}

You can use any CSS selector while nesting with spaces, you can use id selectors with #id-name, tag selectors like h1, pseudo-classes, etc.

Selecting only direct child

If you have the code below and want to apply the color gray only on links that are direct children of the footer, and not the link within the div copyright:

<footer>
	<a href="index">Home</a>
	<a href="blog">Blog</a>

	<div class="copyright">
		<a href="#">website.com</a>
	</div>
</footer>
footer > a {
	color: grey;
}

Selecting only the first child

Let's take the same example above, but now the difference is that you want to apply the hierarchy to the first link only.

<footer>
	<a href="index">Home</a>
	<a href="blog">Blog</a>

	<div class="copyright">
		<a href="#">website.com</a>
	</div>
</footer>

The code below will apply the grey to both the first child of footer and the first child of .copyright.

footer a:first-child {
	color: grey;
}

To apply only to the first child of footer:

footer > a:first-child {
	color: grey;
}

Selecting only the last child

It's quite common in lists to select the last item in the list and give it a different style, without the lower separation border, for example. The code is the same, we just need to change the selector.

<ul class="menu">
	<li>Item 1</li>
	<li>Item 2</li>
	<li>Item 3</li>
</ul>
ul.menu li {
	border-bottom: 1px solid grey;
}

ul.menu li:last-child {
	border-bottom: 0;
}

Did you find this helpful?

Ricardo Metring

Ricardo Metring

Full stack web developer and co-founder at Criar.io.
I've worked for over 10 years with software development. I'm constantly curious and learning.

Related articles