|
Changing Link Styles with CSS
Hey, David:
Some of the Web sites I visit change the color of links
or add an underline when I run the cursor over the link.
For example, when I go to IBM's Web site, the links
are underlined. If I look at the source for an IBM Web
page that adds an underline, I can find the link, but I
don't see anything that would make the underline appear.
Do you know how this works?
-- Doug
The reason the link changes when you run your cursor over
it is because a style is associated with links on that
page, which assigns the underline to links when you hover
the mouse over them. The style is either embedded in the
page or stored in a separate file called a Cascading
Style Sheet (CSS).
A style rule has two parts, a selector, and a rule block.
The style rules defined in the rule block apply to all
elements identified by the selector. A selector is
normally an element, or set of elements. A style rule
that selects anchor elements and changes their color to
blue is written like this:
a {color:blue}
The second release of CSS, known as CSS Level 2, defines
a pseudo-class selector for hover. Pseudo-classes provide
a way for a browser to further identify elements. In
addition to hover, there are pseudo-classes that indicate
link, visited, active, first-child, active, focus, and
lang. The pseudo-class
section of the W3C
CSS specification describes these in detail.
To get the anchor element to change to underlined red
when the cursor is hovering on a link, use a style rule
like this:
a {color:blue; text-decoration:none;}
a:hover {color:red; text-decoration:underline;}
Style rules can be entered directly in the document
inside of a style element. You can also define style
rules in an external document and link that document to
your HTML document. To embed your rules internally,
include the following style element in the head element
of your HTML document:
<html>
<head>
<style type="text/css">
<!--
a {color:blue; text-decoration:none;}
a:hover {color:red; text-decoration:underline;}
//-->
</style>
</head>
<body>
<p>Here is a link to <a target=new
href="http://www.itjungle.com">Midrange
Server</a></p>.
</body>
</html>
Cut and paste this example into Notepad and save it with
an .html extension to try this out. An external style
sheet contains the same rules and is referenced using a
link element in the head element of your HTML document,
such as this:
<link rel="stylesheet" href="/styles/standard.css" type="text/css">
In this case, the standard.css document in the styles
directory contains the style rules, which are not
embedded in elements. The contents of the standard.css
document are as follows:
a {color:blue; text-decoration:none;}
a:hover {color:red; text-decoration:underline;}
Using an external CSS document is generally better,
because most browsers cache the contents of CSS
documents. This helps reduce the size of HTML pages and
improves overall response time.
-- David
|