Once you understand the basic structure of CSS – selector {property: value;} – you can begin using it to style elements in your html documents. There are certain elements in html that we use all the time; p for paragraphs, h1 h2 h3 for headings, ol and ul for lists…all of these things can be styled using that syntax. Font color and size, padding, margins, positioning and anything else that you would use to style these elements can be incorporated into your Cascading Style Sheet. The fun part comes when you start designating your own selectors, and that’s what classes and IDs are for.
In CSS, a class is defined by using .classname in the stylesheet, where classname is whatever title you choose to name the element. For example, in the above sentence, I used <span class=”boldtext”>.classname<span> to apply a bold font to the selection. The corresponding CSS code would look like this:
Every time I used the class .boldtext in my document, the enclosed text will be bold. Pretty simple!
By using the ability to assign your own classes, you can have multiple elements share the same styling throughout the page.
Classes can be used more than once in a single page – in fact, the same class can be used as many times as you want.
Giving an element an ID is the same idea, with a couple of differences. With an ID, you replace ‘.’ with ‘#’ and end up with this:
which will do the same thing as the class did – style the element with a bold font. The other difference, and this is important! – is that an ID can only be used once within a page. I use IDs a lot for structual elements, like headers and footers, because those elements are generally only used once in an html page.
If you think of an ID as something unique, like a person’s name, and classes as something that has more than one, like a class of people, then you’ll remember how to use them in writing your CSS.
Now you may be asking – what’s the difference between using <span class=”bold”> in a stylesheet and <span style=”bold”> in your html? You still have to type it into your markup every time you want the text to be bold, right? Well, that is true, but once you get into using multiple values for the same element you’ll see what a difference CSS can make. Imagine that you not only want that text bold, but you want it to be bold, blue and in Comic Sans font. You can combine all of those attributes into one class and save yourself the headache of writing out all three styles every time you want that particular styling.
Your CSS would look like this:
and your html would look like this:
We’ll get further into multiple properties in another post.
Trust me, when you’re adding margins, padding, colors, backgrounds, positioning and font attributes all to one element, you’ll love using CSS!
