Home » Tutorials » CSS » Classes

Classes

The most important part of CSS is correctly assigning the HTML to a particular CSS class or by using the proper selector. You link any CSS on an element unless that element acknowledges that it is linked to some styling properties. Classes can be used to construct hierarchies that sub classes can immediately inherit, but for now, we will just use simple top-level classes. Some CSS selectors can be very specific to an element, but we will start with CSS classes.

Element Classes

Example
<style type=”text/css”>
div.special {
color:#900;
}
</style>

<div class=”special”>
Sample Text
</div>
Result
Sample Text

We simply set our div class attribute to “special”. That reference provides a reference to our CSS div.special class, which is called that because it is an HTML div element and a class reference in CSS takes a .className syntax. So, if we changed our div to a p tag, we would put p.special in our CSS. However, if you wanted a class that did the same styling to every element that referenced it, you could leave off the element name before the .special. Now, every element that had a class attribute set to “special” would inherit these styling properties.

CSS Selector Id

Example
<style type=”text/css”>
#special {
color:#900;
}
</style>

<div id=”special”>
Sample Text
</div>
Result
Sample Text

Clearly, the id attribute is our selector here, but you should only assign 1 id to an element. It is terrible practice to have a whole bunch of elements with the same id and sometimes it confuses the browser. While you continue to grow as a CSS pro, the difference will become clear. If you want to style multiple elements, use classes. If you only want to style one element, use the specific id selector.

References



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Classes". After Hours Programming. Accessed on March 16, 2024. https://www.afterhoursprogramming.com/tutorial/css/classes-css/.

  • Stewart, Suzy. "Classes". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/css/classes-css/. Accessed 16 March, 2024.

  • Stewart, Suzy. Classes. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/css/classes-css/.



1 thought on “Classes”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.