CSS 101

Custom Selectors

What we lost in the previous step was the ability to target a single paragraph. Our new page-wide rule applied to all paragraphs on the page -- but what if we need the occasional ability to make a particular paragraph stand out? CSS makes this easy, through the use of the "class" and "id" constructs. By attaching a "class" name to an HTML element, and writing a corresponding rule for that class, you can get as specific as you like. Modify the style rules at the top of your document to look like this:

    p {
        color:black;
        font-size:12px;
        font-family:Verdana;
    }
    
    .alert {
        color:darkred;
        background-color:bisque;
        border:2px solid gray;
        padding:10px;
    }    

Now, modify the opening <p> tag of one of your paragraphs to look like this:

<p class="alert">Lorem ipsum ... </p>

The result should be this - a single paragraph on your page that gets additional stylistic information.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

So what just happened? The "special" paragraph actually got instructions from two selectors. It's a paragraph, so it inherited the rules for all paragraphs, and it had class="alert" attached to it, so it inherited those rules as well. Another interesting thing about this is that the rules for both p and .alert specified a color - black for paragraphs and darkred for anything in the class ".alert". Only one of them could win, so the cascade kicked in. The class declaration was more specific than the general rule for paragraphs, so it won.

OK, here comes the cool part. Go to a second paragraph somewhere in your document and attach class="alert" to that one as well. Voila! Now you have two custom-styled paragraphs in your document, even though you've only established one ruleset. The rule you've created is the .alert { ... } section in the style section at the top of your document.

The selector you're using is anything with class="alert" attached to it. Anything? Darn near. Try attaching that same class to a blockquote on your page, or to a list. Same effect, different element. Pretty cool.

Add your comment

Login to post a comment.