2

Is there a way to have a class or any selector with specific styles, and then share, import or assign those styles to a another selector. This is to avid creating multiple classes and not having to go back to the HTML code all the time to assign such classes.

For example:

.orangeText{
 color:orange
}

.strongtext{
 font-weight:900
}

a regular scenario would use those clases like this:

<div class="orangeText strongtext">My orange Strong Text</div>

I am looking for something like this:

.orangeText{
 color:orange
}

.strongtext{
 font-weight:900
}

.orangeStrongTitle{
  @.orangeText; /* Import styles from .orangeText*/
  @.strongtext; /* Import styles from .strongtext*/
  text-decoration:underline;
}

ON HTML:

<div class="orangeStrongTitle">My orange Strong Text</div>

PLEASE NOTE THAT @.orangeText IS MY INVENTION TO GIVE AN EXAMPLE OF WHAT I WANT, I DON'T KNOW IF SUCH THING EXISTS, I WAS INSPIRED ON @import

Is this possible?

multimediaxp
  • 9,348
  • 13
  • 49
  • 80
  • 1
    Use LESS. With that you can literally just put `.orangeText; .strongtext; text-decoration: underline;` and it'll compile to the appropriate CSS. Takes some setup but it does make things a lot easier (especially the nesting feature). – Niet the Dark Absol Mar 27 '19 at 00:20
  • Also u can use SASS – Grzegorz Miśkiewicz Mar 27 '19 at 00:24
  • Thanks @NiettheDarkAbsol, I am looking for a vanilla solution, I don't have the option right now of installing or using third party libraries, but please add your solution as answer with a working example and I will definitely up-vote your answer. – multimediaxp Mar 27 '19 at 00:24
  • Thanks @GrzegorzMiśkiewicz, same thing please add a working example as an answer and I will up-vote it. Thanks – multimediaxp Mar 27 '19 at 00:27

1 Answers1

4

With traditional CSS it seem's that you can't.

See this topic : Is it possible to combine classes in CSS?

Unless you use LESS or SASS's 'mixin' features, there's no real way in plain CSS to "inherit" other classes. The best you can do is apply all three classes to your DOM element. If your problem is that you have a ton of those classes already on a page and you want to add properties to all of them, you can do:

.foo, .bar, .foobar {
    color: red;
}

and that will apply color: red to any element that has .foo or .bar or .foobar.

EDIT

Since you're asking for an exemple, here is how the mixin feature of SASS works :

@mixin mixin-name {
  margin: 0;
  padding: 0;
}

ul {
  @include mixin-name;
}

Having this will compile into this :

ul {
  margin: 0;
  padding: 0;
}
Thomas
  • 108
  • 8