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 Basics (2014) Basic Selectors Class Selectors

Kenneth Simpson
Kenneth Simpson
1,162 Points

Why classes instead of just using the element tags for selectors?

I understand that classes can be useful when you can use them to style more than one element the same without having to type separate css rules for each element. What I do not understand is why use classes for selecting certain elements if you are only going to be styling that specific element a certain way? Why not just use the element tag and select that?

Thanks.

3 Answers

Thas Eagans
PLUS
Thas Eagans
Courses Plus Student 2,533 Points

Typically u do just target that element. The point where you run into issues is when you have more than one of that element within your page. Lets say you have 3 paragraphs of text, and you only want to style each paragraph with a different border.

<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>
/* this will affect "every" paragraph on the page which is NOT what we want */
p {
  border: 2px dashed #ccc;
}

If we instead use a class, we can target exactly which paragraphs we want to affect.

<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p class="solid">This is paragraph 3</p>
/* all paragraphs without .solid will have a dashed border */
p {
  border: 2px dashed #ccc;
}
.solid {
  border: 2px solid #ccc;
}

Hopefully that helps.

</TREagans>

Kandance Ferguson
Kandance Ferguson
6,271 Points

When you have multiple tags of the same element, say for instance multiple paragraph elements, using classes helps to keep your code neat, clean, and non-repetitive. In addition, when you want to make changes to those elements, you can target all of the tags at the same time, rather than having to make the change to each one separately.

Kenneth Simpson
Kenneth Simpson
1,162 Points

I did not even think about that. That makes perfect sense. Thank you for your responses!