CSS (Cascading Style Sheets) is used for styling your site. It gives a wide variety of options, allowing you to change the size and style of fonts, colors, images and the positioning of elements on the page.
Identifying an element in CSS can be done in a number of ways. You can affect all instances of a tag, such as paragraphs, headers or links. You can also be much more specific by using an ID or a class.
So what's the difference between an ID and a class?
Using a CSS ID
Suppose you have a site with a header, navigation bar, content section and footer. The basic HTML for your site (minus the <body> tag and everything outside it) might look something like this:
If you wanted to style just the header, then you could do this:
Note the # symbol - this means that we want to affect the CSS ID. #header means that we want to affect the element with the ID "header".
Using a CSS Class
If you wanted to style the "bubble" boxes, the following code would achieve this:
Note the period "." - this means that we're working with a class. .bubble means that we want to affect all elements with the class "bubble".
Although you can apply the same styles regardless of whether you're using an ID or a class, it's important to understand the differences:
- ID must only be used for one element on a page; class can be used for many elements on a page
There's more you can do with the ID of an element, but that's a topic for another tutorial.
How To Choose
Use an ID for elements of the design that only appear once, such as your header and footer.
Use a class for elements that may appear many times on the same page but that need to be styled differently to the standard HTML tags. So you might use a class for an info box or a user avatar, but not for a standard paragraph of text.
If you are changing a site that you didn't create, be very careful when editing IDs and classes. Not only can this break the site design, changing the ID of an element can break functionality. Test, test and test some more before pushing your changes to a live environment.
Photo by jeffisageek