简体   繁体   中英

how to combine multiple css class selectors into one?

I have a few selector classes eg

  • .rt-grid-6 { ... }
  • .largemargintop { ... }
  • .rt-left { ... }

I have to use them in couple of elements in my html

sample

<div class="rt-grid-6 largemargintop rt-left">
    ...
</div>
<div class="rt-grid-6 largemargintop rt-left">
    ...
</div>
...

so this is being repeated and difficult to manage, if I have to add or remove a class then I have to update all the occurrences

so I was thinking if the below mentioned css is possible in some way

.item
{
    rt-grid-6; //refer to the mentioned class
    largemargintop;
    rt-left;
}

and I can use them as in the sample below

<div class="item">
    ...
</div>
<div class="item">
    ...
</div>
...

I can define a new .item class for the same with the values but the problem is I can not change the existing classes and at the same time I have to use the style define in the respective classes.

I can not use less as I can not redefine the style or have access to sources. I only receive a compiled css to use as is.

So is there any possible way by which I can achieve the desired?

solution may not be necessary in the way I mentioned, but I want to increase the maintenance so that it is easier to add or remove the classes to the desired elements from a single point.

With only CSS is not possible. You must use a CSS compiler like SASS or LESS .

You can see a guide: http://sass-lang.com/guide

An example with SASS :

.item
{
    @extend .rt-grid-6; //refer to the mentioned class
    @extend .largemargintop;
    @extend .rt-left;
}

Very simple!

In SASS you can use variables, and much more! It's very usefull.

Since you cannot use less or sass, what you can do is use a temp css class name and replace it using jQuery like following code,

Html

<div class="temp-class">aaaaaaaaaaaaaa</div>
<div class="temp-class">bbbbbbbbbbb</div>

JS

$(".temp-class").attr("class", "rt-grid-6 largemargintop rt-left");

Demo

try using SASS / LESS to overcome this. What you are using won't work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM