Reputation: 11974
We have a style defined in our CSS with several attributes.
Now we have to define a new style, with the same attributes, the only difference is font-size: instead of 20px it should be 16px.
1) Should we define a new style in the CSS? Is there a way to inherit everything else? 2) Or, do we override "font-size" directly in HTML/JSP. This can work but is not very elegant.
.loading-text {
font-family: "Trebuchet MS";
font-size: 20px;
font-style: bold;
color: #196198;
max-width: 450px;
}
.loading-text-smaller {
font-size: 16px;
}
Upvotes: 0
Views: 58
Reputation: 26380
You can define multiple CSS classes at once, then modify one of them.
.loading-text, .loading-text-smaller {
font-family: "Trebuchet MS";
font-size: 20px;
font-style: bold;
color: #196198;
max-width: 450px;
}
.loading-text-smaller {
font-size: 16px;
}
The font-size rule in .loading-text-smaller will override the rule set the first definition. Otherwise, they will be identical.
As others have pointed out, you can also use multiple classes on an element and that works fine. My thought to add to that is to be sure to add the more specific class definitions after the general one. If you were to define .loading-text-smaller
and then define '.loading-text', the font-size rule in .loading-text
might override the other font size rules previously defined. Order of definition matters.
Upvotes: 1
Reputation: 14580
Your CSS code will work as-is if you use class="loading-text loading-text-smaller"
on your elements.
Alternatively, you can add styles for multiple classes, and then override with subsequent styles
.loading-text,.loading-text-smaller {
font-family: "Trebuchet MS";
font-size: 20px;
font-style: bold;
color: #196198;
max-width: 450px;
}
.loading-text-smaller {
font-size: 16px;
}
You can also use CSS child selectors to override properties when your element is contained in another class of parent, e.g.
.loading-text {
font-family: "Trebuchet MS";
font-size: 20px;
font-style: bold;
color: #196198;
max-width: 450px;
}
.small-parent .loading-text {
font-size: 16px;
}
in the last case if you have
<div class="small-parent">
<div class="loading-text">some text</div>
</div>
The text will be 16px
Upvotes: 1
Reputation: 16184
You could use an Attribute Selector to style all elements who's classname contains the string 'loading-text'. This would then apply to both .loading-text
and .loading-text-smaller
without the need to assign both classes to your element.
*[class*="loading-text"] {
font-family: "Trebuchet MS";
font-size: 20px;
font-style: bold;
color: #196198;
max-width: 450px;
}
.loading-text-smaller {
font-size: 16px;
}
Upvotes: 0
Reputation: 588
I would avoid using !important if you can, it's far too aggressive and should be only be used in dire cases.
There's nothing wrong with having a separate class and assigning both classes to the element. Ie:
<span class="loading-text loading-text-smaller">Loading...</span>
Upvotes: 2