CSS 101

Class vs. ID

Above, we mentioned that there were two constructs for custom selectors -- "class" and "id." You've seen that a class can be applied as many times as you like on a page. IDs work almost the same way, but apply to just one element on a page. When creating rules for IDs, simply prepend the selector name with "#" rather than "." For example:

    #footer {
        color:darkred;
        background-color:bisque;
        border:2px solid gray;
        padding:10px;
    }    

Since you will probably only ever have one footer on a page, it makes sense to use this as an ID rather than as a class. You would invoke this ruleset in your document like this:

<p id="footer">Lorem ipsum dolor sit ... irure dolor in reprehenderit in </p>

Recap: When writing CSS rules, you don't have to specify an existing HTML tag as a selector. If you start any word in a ruleset with a dot ("."), it becomes a custom selector called a "class", which can then be applied to anything on the page. In our example, we used the word ".alert" in our ruleset, prepended it with a dot, and it became the rule for the selector "alert". Similarly, we can address a single element on a page by referencing with an ID rather than a class. Rules for IDs use the "#" syntax rather than the "." syntax. In general, you'll use IDs when elements are guaranteed to be unique on a page, and classes when they're not.

The ability to style any existing HTML element, combined with the ability to create custom, named selectors, gives you complete design and display flexibility.

Add your comment

Login to post a comment.