Dan Kanze
Dan Kanze

Reputation: 18595

multiple IDs sharing 1 class CSS

I could do something like:

#id1 .class1, #id2 .class1{
   color:#FFF;
}

But that seem's bulky, especially if I have a ton of ID's I want to share with 1 class.

I'd much rather do something like:

#id1, #id2 .class1{
   color:#FFF;
}

Obviously this doesn't work, but you get my drift.

Thoughts?

EDIT:

Probably should have mentioned I am over-riding CSS framework before I got flamed. Think bootstrap or zurb foundation. That's why there is a need to do this instead of just using a class. I was just wondering if there was any other inheritance selectors I wasn't aware of in native CSS.

Upvotes: 0

Views: 1947

Answers (5)

Jon Jaques
Jon Jaques

Reputation: 4400

I suggest doing some reading about CSS specificity.

http://css-tricks.com/specifics-on-css-specificity/

First try writing a specific enough selector that will override the CSS framework.

This may involve doing something like

html body .class-i-want-to-override { /* ... */ }

It may require putting an !important on there, although that should be your last resort.

.my-class { color: pink !important; }

Finally I would suggest looking into a CSS preprocessor like SASS. This would allow you to write in a more efficient manner.

#special1,
#special2,
#special3 {
  .override {
    color: pink;
  }
}

Which would get compiled to:

#special1 .override, #special2 .override, #special3 .override {
  color: pink;
}

Upvotes: 1

Paul
Paul

Reputation: 141829

You can use a language like LESS which compiles to CSS. Just one of it's many features is that the following LESS:

#id1, #id2 {

  .class1 {
      color: #fff;
  }

}

Compiles to:

#id1 .class1,
#id2 .class1 {
  color: #fff;
}

That compilation can be done server-side (lessphp or less.js) or client-side (less.js) depending on your preference/needs.

Upvotes: 2

Sander-Martijn
Sander-Martijn

Reputation: 11

You're overthinking it. The point of classes is to cover multiple items. all you need to say is:

    .class1{
       color:#FFF;
    }

this only won't work directly in 2 cases.

  1. you have the class appearing elsewhere. Find (or create) a unique element surrounding your classes, such as

    ul .class1{
      color:#FFF;
    }
    
  2. you have the class showing up on other types of elements. In this case:

    li.class1{
      color:#FFF;
    }
    

Upvotes: 1

Anders Lindén
Anders Lindén

Reputation: 7293

What about this?

.class1
{
  color:#FFF;
}

Upvotes: 2

Fernando Jorge Mota
Fernando Jorge Mota

Reputation: 1554

Why not just use a class?

Or apply, in the elements with these ID's, a common class? As a element can have a ID and classes at the same time..

In the code below is a basic example:

#commonClass .class1{
   color:#FFF;
}

Upvotes: 0

Related Questions