News Tutorials Projects Reviews Authors Contact Search Links Admin
 

CSS Introduction : Selectors

Another useful set of functions in CSS are selectors. So far we've been using basic element selectors. E.g. h1 { }, to select all <h1> tags, and apply properties to it.

What if you've got two <h2> tags, and you want to apply a different style to each of them? How can you change the properties between the two?

Class and ID Selectors

Classes and IDs are very specific selectors. In HTML they look like this:
<h1 class="pagetitle"> <h1 id="note">
Simply, in HTML they are attributes added to each tag.

In CSS, you can now specify these tags types more precisely.

h2.pagetitle {
color: black;
font-size: 16pt;
font-family: Verdana, sans-serif;
}
h2#note {
color: red;
background-color: inherit;
}
.code {
color: green;
}

H2 class Pagetitle

H2 id Note

SPAN class Code

This would make <h2 id="note"> have red text, and <h2 class="pagetitle"> have size 16pt, Verdana faced text. Both <h1> tags, but different styling. The 'code' class would apply to any tag with the class='code' attribute, making the font green.

Tags can have a Class, and an ID. e.g. <h1 class="pagetitle" id="note">. In this case, the <h1> tag would be size 16pt, Verdana, and Red. This is because ID's are more specific then classes. The order has nothing to do with it. Because ID's are more specific, their attributes are used ontop of the preference of other selectors.

Pseudo-Class Selectors

:Hover :Visited :Active are all examples of Pseudo class selectors, and for most browsers they only apply to <a> hyperlinks.

a {
color: navy;
background-color: white;
text-decoration: none;
}
a:active {
color: green;
}
a:visited{
color: navy;
}
a:hover {
color: red;
}

All of ^ that means..
- Default links will look navy/dark blue.
- When you hover/rollover a link it will turn red.
- When you activate a link (by clicking or tabbing) it'll turn green.
- When you've visited a link already, the link will turn dark blue.

A bit like the links on mkv25.net.

Now, go on.. try it! Use this code below, and put it into a HTML document.


<html>
<head>
<title>My first CSS</title>
<style>
body {
font-family: Arial, Verdana, sans-serif;
font-size: 11pt;
}
a {
color: navy;
background-color: white;
text-decoration: none;
}
a:active {
color: green;
}
a:visited{
color: navy;
}
a:hover {
color: red;
}
</style>
</head>

<body>
<p>In the middle of the page, is the first example of my CSS hover link. <a href="http://mkv25.net">Click here</a> to visit mkv25.net.
</p>
</body>
</html>

 


Author: Markavian
Last edited on: 5th Dec, 6:53 pm
Please rate this article.

« Prev page 'CSS in HTML' « » Next Page 'CSS Properties' »

tutorial Pages