7

Quick question which is mostly explained by the code.

Is this possible in CSS or do I have to just implement all the classes in the html?

.class1{
    color:red;
}
.class2{
    text-decoration:underline;
}
.class3{

    class1;
    class2;
    border:1px solid green;
}

3 Answers 3

8

You can use a CSS pre-processor like LESS or SASS for CSS "class inheritance".

Otherwise, your code sample is not possible with pure CSS. You can, however, use a comma to add similar styles to multiple elements:

.class1, .class2 {
    /* your styles */
}
Sign up to request clarification or add additional context in comments.

Comments

4

It is not possible to do it as such. If an element needs to have multiple classes, just specify it in the HTML :

<span class="class1 class2">Test</span>

Note that it is possible to define a selector for elements having multiple classes. .class1.class2 selector would target the element in the example here above, while not targetting elements that don't have both classes specified in HTML. This is usefull for example if you wish to override one of the properties of 1 of the classes only when they're used in combination.

Comments

3

One approach you can use is to implement it through JS itself.

I would recommend using something like JSX it will simplify the process.

You can set a variable somewhere within scope and list your classes

const buttonStyle = "class-1 class-2 class-3"

Applying the style using JSX (Provided you use it)

<button id="my-button" class={ buttonStyle } />

Applying the style using JQuery (Provided you use it)

$("#my-button").addClass(buttonStyle)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.