tags:

views:

116

answers:

4

Say I have a div that uses two css classes that both use text-align, but one is centered and the other is right aligned.

Is it possible to specify something that will give one class priority over the other?

+4  A: 
  1. !important
  2. assign it after the other class
  3. specify a more specific selector, eg prefix an ID before it or prefix the nodename before the class
meder
+1 But I'd switch 1 and 3; `!important` is a little hackey compared to using CSS specificity.
LeguRi
+1  A: 

Yes, you can find the exact rules here.

mjw06d
+1  A: 

You should use CSS specificity to override previous declarations http://htmldog.com/guides/cssadvanced/specificity/

p = 1 point
.column = 10 points
#wrap = 100 points

So: p.column { text-align: right; } can be overwritten by: body p.column { text-align: left; }

Johan
A: 

If you want to be explicit about it, you can specify how the combination of those two classes work together, by supplying a rule for elements that contain both classes. For instance, you can explicitly give something with both classes foo and bar the same styling as just bar as follows. This works because .foo.bar is more specific than just .foo for elements which have both classes, and thus this rule will take precedence over the .foo rule.

.foo { text-align: center }
.bar, .foo.bar { text-align: right }

If you don't want to be this explicit, you could just place the rule for bar after the rule for foo, as given selectors of the same specificity, later rules take precedence over earlier ones:

.foo { text-align: center }
.bar { text-align: right }

You can learn more about how precedence between rules is determined in the CSS specification chapter about the cascade; that's the "C" of CSS, and is important to understand well in order to take full advantage of CSS.

Brian Campbell