Using CSS Classes
<td class="blue">
<a href="lnk1.aspx">Hi1</a>
<a href="lnk2.asp开发者_C百科x">Hi2</a>
<a href="lnk3.aspx">Hi3</a>
<div>Not Blue</div>
</td>
I want the class in the tag ("blue") to make Hi1,Hi2 and Hi3 blue.
So what should be the head of that class?
????
{
color:blue;
}
Using a descendant selector:
td.blue a {
color: blue;
}
Or if you only want it for immediate children, a child selector:
td.blue > a {
color: blue;
}
Reference material:
- Selectors supported by most browsers: CSS 2.1
- Newer selectors supported by some browsers and by various JavaScript libraries (for interacting with the DOM): CSS3 Selectors
Use the following. This means all a
elements within any td
element that has a class name of blue
should be displayed in blue.
td.blue a {
color:blue;
}
However, you should note that semantically it is unwise to give your CSS classes style-specific names (like 'blue' or 'bold' or 'center') - if later you decided to change the colour to red, you would have to change all references to the blue
class to red
(potentially lots of work) or instead be left with really confusing class names that don't make sense.
Try naming the class after what the elements in question mean. So in this case, it might be td.links
for example.
The CSS selector you need would reference both the blue
class and the a
tags beneath it.
.blue a {
color:blue;
}
Note that there is another syntax which you may also want to consider:
.blue>a {
color:blue;
}
note the >
between .blue
and a
in this example. Both examples will work for your given HTML code, but this version more specific than the first, because it only affects <a>
tags that are immediate children of blue
. In other words, if you had an <a>
tag inside the <div>
, the first version would affect it, whereas this version wouldn't.
The downside is that IE6 doesn't support the >
selector, so if you need to support IE6 users, you must use the first version. Fortunately, IE6 users are becoming fewer, but there are still a few of them out there.
One other thing: I'd also advise you to avoid using class names which refer to the actual colour. It's usually better to call it menulink
, or something like that.
The reason for this? Imagine in the future you want to change your site a bit, freshen it up for a new version. Maybe new corporate colours afer a rebranding exersise. Whatever. You could do that without an change at all to your HTML code; just a CSS update:
.blue a {
color:red;
}
...but now your CSS doesn't make sense. If you'd called it menulink
, you will always know what that class refers to, even if things change over time.
Try this.
td.blue a {
color: #0000FF;
}
This sets all a tags that are within a td tag with a class of blue.
精彩评论