Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy css from one class to another?

This may seem like a very basic question but I did not seem to find an answer to it. I know it is possible to define a css rule for more than one element at once as such:

.element1, .element2{
  font-size:14px;
}

Is it possible, though, to do that exact same thing, but apply the css to element after the css for element1 has been defined? Something like this:

.element1{
  font-size:14px;
}

/*later in the css... or in a separate file*/

.element2{
 like:".element1";
 font-weight:bold;
}

So that element2 now inherits the css of element one. The reason I am trying to do this is because I have a css definition for an element1 that loads for all pages of the site. Then, for one particular page (that loads the main css file, along with its own) I would like to use the style from element1 and add to it. What I am trying to avoid is loading the definition for element2 for all pages on the site (including those who don't even have element[s] with the class element2.

Could this be done? I realize I could easily achieve this with jQuery (i.e. $(".element2").addClass(".element1");) but I would like to avoid using scripts for my css.

Thanks!

like image 748
Yuval Karmi Avatar asked Jul 31 '09 09:07

Yuval Karmi


2 Answers

You can use:

<div class="element1 element2">

while having

.element1{
  font-size:14px;
}

.element2{
  font-weight:bold;
}

and so both classes will apply. jQuery is smart enough to add classes and remove classes like this.

Also you can use something more advanced like SASS that alows mixins.

like image 128
Silviu Postavaru Avatar answered Sep 19 '22 12:09

Silviu Postavaru


As far as I'm aware, no, this isn't possible with CSS alone. You've already identified one way of achieving your aims, and I'd have to suggest that it's the better way.

In CSS a class can only inherit from its parent, and then only if <example-attribute>: inherit; (I've used this with color:, background-color:, font-family:, font-size: among others, though I warn you that if the font-size of the parent a size described as an increase or decrease, the font-size will change in the child, too.

like image 34
David Thomas Avatar answered Sep 19 '22 12:09

David Thomas