tags:

views:

111

answers:

6

If I define a CSS attribute in both a CSS class and inside an element directly, which value ends up being used?

Let's use width as our example

<html>
<head>
 <style type="text/css">
  .a {
   width: 100px;
  }
 </style>
</head>
<body>
 <div class="a" style="width: 200px;"> </div>
</body>
</html>

What should the width of the div be in a browser? (according to the standard, not what happens in practice)

+3  A: 

Cascading (hence its name) says it's element's preference over in-file styles over referenced file styles.

Robert Koritnik
+2  A: 

The "style" attribute will trump the class selector.

See the ever useful Selectutorial for a walkthrough of how conflicting rules are resolved. See also the CSS2 specification section on specificity

Paul Dixon
+1  A: 

The element's style will be used as it has a higher specificity.

The specificity rules:

  • element style: 1000 points
  • id: 100 points
  • class: 10 points
  • element name (table, div, etc.): 1 point

Examples:

  • .class is 10 points
  • table.class is 11 points
  • div#myId.class is 111 points
  • div is 1 point

The declaration with the most points will be used. However, you could override styling placed at any level by using !important.

geowa4
+1  A: 

It should be 200px. The rule defined here says that if the "if the declaration is from is a 'style' attribute rather than a rule with a selector" then that's the highest priority/specificity.

ChrisW
+1  A: 

the defined value on the element should prevail...

Anthony Shaw
+1  A: 

About that question, you can take a look at the specification ; especially section 6.4.3 Calculating a selector's specificity. Section 6.4.1 Cascading order will probably be usefull too.

The "style" attribute is the last one to be declared and the most specific ; so this is the one that should be used.

Pascal MARTIN
It's used because it's the most specific, not because it's the last one declared; knowing which one is the "last" one would only be significant between rules of otherwise-equal specificity.
ChrisW