Annapoorni D
Annapoorni D

Reputation: 849

width attribute of td is not overriding css width property

I have searched about this pretty much and still not able to understand the reasong for the behaviour. I have a td element with width attribute specified and I also have specified the width in css class. But the width in css class is reflecting, doesn't the width attribute of element take higher priority?

Sample code:

<table class="sample">
  <tr>
    <td width="70%" class="cell">First cell</td>
    <td class="cell">Second cell</td>
  </tr>
</table>

Css

table.sample {
  border: 1px solid red;
  width: 100%;
}
td.cell {
  border: 1px solid black;
  width: 40%;
}

I understand that width attribute is deprecated and not advisable to use, I am trying to understand the behavior as I have to fix a similar issue, where I have many pages using the style td.cell but I need to override it in one page, I can go for style attribute that is one way, or define another style class.

Upvotes: 2

Views: 8512

Answers (3)

Pranav
Pranav

Reputation: 8871

When you write <td width="70%" class="cell">First cell</td> and once Browser will parse this line it will generate one column having property as width. but when you write like

<td style="width:70%" class="cell">First cell</td>

it will become one attribute of the style , Hence a kind of as you say inline CSS. So your External CSS cannot override it now.

try like this :-

<table class="sample">
  <tr>
    <td style="width:70%" class="cell">First cell</td>
    <td class="cell">Second cell</td>
  </tr>
</table>

Simply writing Width in mark up defines it as a property. So your Css is overriding this...

See this :- Difference between property and attribute
and this is the answer for your query :- Should image size be defined in the img tag height/width attributes or in CSS?

Upvotes: 0

Alohci
Alohci

Reputation: 82976

From the CSS 2.1 spec

6.4.4 Precedence of non-CSS presentational hints

The UA may choose to honor presentational attributes in an HTML source document. If so, these attributes are translated to the corresponding CSS rules with specificity equal to 0, and are treated as if they were inserted at the start of the author style sheet. They may therefore be overridden by subsequent style sheet rules. In a transition phase, this policy will make it easier for stylistic attributes to coexist with style sheets.

So CSS styles always out-rank presentational attributes in HTML.

Upvotes: 2

Archna Rangrej
Archna Rangrej

Reputation: 664

<table width="100%" class="sample">
  <tr>
    <td width="70%" class="cell">First cell</td>
    <td width="30%" class="cell">Second cell</td>
  </tr>
</table>

Css :-

table.sample {
  border: 1px solid red;
}
td.cell {
  border: 1px solid black;
}

Upvotes: 1

Related Questions