![](http://images-20200215.ebookreading.net/24/3/3/9781498731454/9781498731454__start-programming-using__9781498731454__bg4a.png)
4.2 Cla ss Selectors
Professor: Let me briefly summarize what we have learned about CSS so far. You
can style H TML elemen ts using CSS rules. A CSS rule consists of two basic parts: a
selector and a declaration block. Although the de claration block takes car e o f all the
formatting, the real p ower of CSS hides in the selec tor. With the selector, you take
charge of your page’s appearance , telling CSS what it is you want to style.
The type of selector that we learned abou t in our last meeting is the most general
one. At the same time it is also the simplest to use and understand. Because it le ts
you select elements only according to their names, it is called an element selector
(sometimes also a tag or type selecto r). It is not hard to id entify element selectors
in a CSS rule, for they are named after the elements they style . For example, body ,
p, h1, a, and so forth. Although they are efficient and easy to use, element selectors
have their drawbacks. In your homework, for example, you stumbled upon a problem
of how to right align a hyperlink within just one paragra ph while keeping text inside
other paragraphs left aligned. That is som ething that you cannot do with an element
selector.
Mike: What about an inline CSS declaration? We can use it to style a single element
instance, can’t we?
Professor: Technically, yes. Bu t even if you want to style a single element, it is not
recomme nded to use inlin e declaration. For one thing, using inline CSS means mix ing
structure (HTML) and presentation (CSS), which is considered bad style. Apart from
that, you will often want to repeat the same single ele ment instance stylin g in more
than a single file, as you can imagine could happen with the Continue... hyperlink
from your homework. A more elegant way of tackling the problem is using a so-
called class selector. You create a class selector simply by making up an appropria te
name for it, preceding it with a period (.). For example, let’s name our class continue
and construct the following rule with the continue class a s a selector:
.continue {
text-align: right;
}
Notice that a declaration bloc k is no different than that used with element selectors.
There is, however, an additional step req uired if you want that to work. The browser
won’t know what you want to style unless you explicitly mark an HTML element you
wish to style. For that purpose you use the class global attribute on the element. Like
this:
<p class="continue"><a href="#">Continue...</a></p>
Be careful not to include a pre ceding period with the value of th e class attribute. A
dot is not a par t o f a class name, but it is used in a CSS rule to signal that a class name
follows rather than an element name.
54 Meeting 4. More Contr ol over Style