CSS: Style Applied to a Combination of Classes

CSS: Style applied to a combination of classes?

$('.bold_green.bold_blue').addClass('something-else');

Or in CSS:

.bold_green.bold_blue { color: pink; }

Notice there's no space between the selectors.

Using two CSS classes on one element

If you want two classes on one element, do it this way:

<div class="social first"></div>

Reference it in css like so:

.social.first {}

Example:

https://jsfiddle.net/tybro0103/covbtpaq/

Defining styles for combinations of classes

You can select on multiple classes:

span.red.green { color: yellow; }

That will apply to any span element with red and green classes. Which may not be what you want, since it will also apply to, say:

<span class="red green blue">white</span>

Note that this doesn’t work right in IE 6.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like Internet Explorer 6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this snippet:

* {
color: black;
}

.foo.bar {
color: red;
}
<div class="foo">1. Hello Foo</div>
<div class="foo bar">2. Hello World</div>
<div class="bar">3. Hello Bar</div>

Can a CSS class inherit one or more other classes?

There are tools like LESS, which allow you to compose CSS at a higher level of abstraction similar to what you describe.

Less calls these "Mixins"

Instead of

/* CSS */
#header {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}

#footer {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}

You could say

/* LESS */
.rounded_corners {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}

#header {
.rounded_corners;
}

#footer {
.rounded_corners;
}

Apply CSS rules only if set classes are present, and not others

Try this one. It will apply only on where the class name matches.

div[class*="ab"]{

/* Write your style that you want to apply */

}


Related Topics



Leave a reply



Submit