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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With