how to combine multiple css class selectors into one?

我怕爱的太早我们不能终老 提交于 2021-02-10 20:22:37

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/25381072/how-to-combine-multiple-css-class-selectors-into-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!