WebWork Unit 4: NavBars – Lesson 3 – CSS Selectors

You can select common objects in your html code and style them all at once using CSS Selectors.

There are three CSS Selectors you will need to know. These are, in order of cascading priority (remember cascading styles?????);

element – the element selector selects all html elements of a certain type and applies the style to all of them in the page.  So yo can select <p> to apply this style to all paragraphs or <h3> to apply a style to all h3 headings. Example:

p {
text-align: center;
color: red;
}

id – the id selector uses the html tag’s attribute to select one or more html elements in a page: The id starts with a # followed by the id name  ex. #name.  The html element needs to contain the attribute id=”name”, do not use the # in the html element.

<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>

<p id=”para1″>Hello World!</p>
<p>This paragraph is not affected by the style.</p>

</body>
</html>

class – the class selector lets you apply a style to  a specific type of element.  You can specify different styling to various type elements using the class statement preceded by the element type and a period or not, simply by not including the element type and period.

Example – without element type

<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>

<h1 class=”center”>Red and center-aligned heading</h1>
<p class=”center”>Red and center-aligned paragraph.</p>

</body>
</html>

Or you can specify the style only applies to a specific element type.

<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: red;
}
</style>
</head>
<body>

<h1 class=”center”>This heading will not be affected</h1>
<p class=”center”>This paragraph will be red and center-aligned.</p>

</body>
</html>

 

Here’s the w3schools CSS Selector lesson.