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

William Yeung
William Yeung
11,331 Points

Element having both an ID and a Class

So I understand what they are and the differences but I'm just confused as to why sometimes an element is given both an id AND a class when there is clearly only one of that type of element. Wouldn't just an id suffice?

1 Answer

Steven Parker
Steven Parker
231,269 Points

An element might be selected in different ways for different things. Every ID is unique, but it might share a class with other elements.

For example, it might get selected individually (by ID) by some JavaScript code that performs an action when it is clicked, but also selected by class along with several other elements to have some styling applied by CSS.

William Yeung
William Yeung
11,331 Points

This bit was from one of the video, but the header tag has both, and the class "main-header" is the only class named this. I guess I'm just wondering whats the point of also giving it a class when its the only element in that class?

<header id="top" class="main-header">
  <span>Journey through the Sierra Nevada Mountains</span>
  <h1>Lake Tahoe, California</h1>
</header>

I understand that you may need to give it a class if you are trying to group it with other elements for the sake of styling but in this case no other element has this class.

Steven Parker
Steven Parker
231,269 Points

Remember that the video examples serve to illustrate the concepts and things are not always absolutely essential for the use they are shown in. But knowing the technique makes you able to employ them when they are.