Question

I'm trying to create a <table> that doesn't exceed a certain width (let's say 500px), even with borders of any size.

Normally, if I do:

(HTML)

<div>
  <table>
    <tr>
      <td>This is a test.</td>
    </tr>
  </table>
</div>

(CSS)

div {
  width: 500px;
}
table {
  width: 100%;
  border: 10px solid #000;
}

I'm going to end up with a <table> that is 510px wide, since half of the left and right borders will end up on the outside of the <div>. What I want is a <table> that is 500px wide total (i.e., that doesn't exceed the width of its parent/container). So, the left and right borders would each be 10px wide, set inside the 500px-wide containing <div> - therefore the table's remaining content area would be 480px.

I can easily do this type of thing to a <div> by using the CSS declaration "width: auto." I can fake it with a table by adding an extra <div> around it that uses "width: auto" with the border set on that <div>, not the <table>.

However, I'm hoping that a more elegant solution exists (must be cross-browser). Is there one that I'm not aware of?

Was it helpful?

Solution

Set the div to 480px wide and put the 10px border on it. Then set the table to 100% width

OTHER TIPS

Not sure if it'd work, but...could you border the first (left border) and last (right border) TDs (or TR perhaps) instead of the table itself? That should give the same visual result.

Otherwise, I wouldn't lose much sleep over a wrapper DIV.

I don't know if there's a cross-browser solution. The IE box model actually works the way you would want: once you declare the width of an element, that's the width, and then it subtracts from the "inner" width of the element the padding margin and border to give you the declared width.

All of the other browsers do the opposite: they set the element width to the declared width and then add the margin padding and border.

I just tested your code in IE7 and Firefox 3.5 and both appear to be 500px wide even with the 10px black border. It's the older versions of Firefox I'd worry about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top