|
Understanding CSS Selectors
By Stephen Bucaro
A CSS style sheet consists of rules that define how html elements should be
displayed on a webpage. Each rule consists of one or more selectors, one
or more properties, and one or more values that each property
should be set to. An example of a basic selector is shown below.
p
{
font-family: verdana;
font-weight: bold;
}
The selector above is p, which selects html paragraph elements. The
properties of the selected elements are listed within curly brackets. The property
names and values are separated by a colon, and property-value pairs are separated by
semicolons. This rule specifically sets paragraphs font to verdana and sets the
text to bold.
• If you use inline style, you don't need a selector. Shown below
is an example of setting the same rule with inline style.
<p style="font-family:verdana; font-weight:bold;">Paragraph Text</p>
Using inline style defeats the purpose of CSS because it applies only to the
individual element containing the style attribute. CSS was designed to make it easy
to set and modify style for all the elements on an entire webpage, or even an
entire web site. Inline style also defeats another purpose of CSS, which is to
separate content from presentation.
• I use inline style frequently because it has several advantages.
For the specific rules set, it overrides any style rules set at higher levels, and
you don't need to go searching around in style code blocks for the rules.
Class Selector
In most cases, you want to set the style for all elements of a certain type, for
example you might want to set the background color for all span elements. In
that case you would use a class selector. An example of a class selector is shown
below.
.bluebkgnd
{
background-color: blue;
}
Note that In the style rule definition, the class selector's name is prefixed with a dot.
This rule sets the background color of every element with the class attribute bluebkgnd
to blue. After defining the class selector, you go through your html code and apply that
class to each span that belongs to the bluebkgnd class as shown below.
<span class="bluebkgnd">Span Text</span>
|