Reputation: 5670
I'm pretty new to using CSS beyond applying directly to each element. I'd like to know how I should be doing this. (simplified from my actual implementation, but relatively the same). Is it possible to inherit styles somehow?
I have 3 div classes defined, each positioning a div in my page. I've left out the css for these, but the style divide my page into 3 sections.
div.left{}
div.center{}
div.right{}
Now, when a user selects one of the divs, it's then highlighted, so I have css to highlight it.
div.lefthighlighted{}
div.centerhighlighted{}
div.righthighlighted{}
I have to now repeat all the styles from div.left{} to div.lefthighlighted{} and add the styles to highlight, and this has to be done for all three div styles I've defined.
OK, I also have a tags within all three of these divs that I want styled different from all other a tags in my application, but they will be the same for the highlightd divs. This is were things get crazy.
I end up with the following for left, center and right. The worst part of this is that all the a tag styling is the same for left, lefthighlighted, center, centerhighlighted, right and righthighlighted, but I can't figure out how to share all of this.
div.left a:link {}
div.left a:visited {}
div.left a:active {}
div.left a:hover {}
div.lefthighlighted a:link{}
div.lefthighlighted a:visited {}
div.lefthighlighted a:active {}
div.lefthighlighted a:hover {}
Keep in mind, I'm simply putting empty braces here, but in my stylesheet, I've got a bunch of styles defined. Is there a way to say
div.left a:link {
inherit div.right a:link;
or
use div.right a:link;
}
I'm finding myself copying and pasting all the same styles and only changing the class name or the parent class name.
Upvotes: 1
Views: 312
Reputation: 349262
You can group styles by using the ,
(commas) as a separator. Eg:
div.left a:link, div.right a:link {}
/*Newlines don't matter:*/
div.left a:link,
div.right a:link {}
Note that the following does not work as "expected":
/*Expecting to select all links under div.left or div.right*/
div.left, div.right a:link {/*FAIL*/}
Another note about inheritance. Elements inherit styles from their parents. When a new matching selector is encountered, the styles from the parent still apply, unless defined otherwise:
a:link, a:visited, a:active {
color: red;
font-size: 16px;
}
a:hover{
font-size: 20px; /*font-size changed, while the color is still red.*/
}
Upvotes: 3
Reputation: 944545
Give the elements multiple classes.
<div class="left highlighted">
And then just include the changed properties in the div.highlighted
rule-set.
Upvotes: 4