Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Foundations Selectors Using Combinators in Selectors

Soufiane Bdaoui
Soufiane Bdaoui
9,602 Points

Why should i use combinators ( > or + or ~) ?

I can't just add some id or class to the element that i want to style?

Combinators help you create styles that only work when another element follows a specific element. A good example of this is to create top padding for the first paragraph following a heading. Using a combinator lets you style just that element and no more.

3 Answers

Great question. You can do that, of course, but there might be cases where your HTML element ID's change or are different on other webpages, but you want the same style for those elements with different ID's because it looks good.

These combinators are used in situations where you want the style to apply across multiple web pages for certain kinds of situations, not specific elements, and the ID's are different for (example) the first child element below the H1 heading.

The general idea here is that the more specific you make your CSS (like specific element ID's), the more limited it is to the pages it can style. If your CSS selector rules are designed with less specific controls (like first child elements after H1 headings), then they can be applied to more web pages.

And that really is the point of CSS vs. styling directly inside the HTML.

Shoaib Bhimani
Shoaib Bhimani
2,697 Points

yes, you can do that with id and classes but using combinators like you mentioned make life a lot easier :)

But is it really worth it to learn using them? Knowing that we can also use a preprocessors - more professional way to accomplish similar results? Or not? I'm a bit confused..

That's your decision to make, for sure.

But what happens if you need to fix a website you didn't design and they aren't using preprocessors or is using a mixture of hand written CSS and preprocessed CSS? Or what if you must do something custom/tricky that the preprocessor doesn't do?

This is really a basic skill that every designer should know, if not for writing it, at the very least for being able to read it and understand it if you encounter it in the wild.