Using CSS to create table cells of a specific width with no word wrapping

13,381

Unfortunately table elements do not respect overflow, so you will need to apply that to a child element.

edit: I may have spoken too soon, as I can create this effect in FF using max-width and I've discovered this thing which might work for IE. You learn something every day.

edit2: yeah it does work for IE7 at least but there's a serious caveat that you can't have whitespace in the text, they have to be converted to &nbsp;. I think you should probably stick with the <div> solution for sake of cleanliness and compatability.

Share:
13,381
Stacey Richards
Author by

Stacey Richards

Updated on June 22, 2022

Comments

  • Stacey Richards
    Stacey Richards almost 2 years

    In a project have been involved in I needed to render tables with columns of a specific width with only one HTML line per table row (no wrapping). I need each table cell to have a padding of 1 pixel at the top and bottom and 2 pixels at the left and right. The best way I can come up with that works cross browser is to put a div inside a td inside the table in this way:

    <style>
      table.grid { border: none; border-collapse: collapse; }
      table.grid tbody tr td { padding: 1px 2px; }
      table.grid tbody tr td div { overflow: hidden; white-space: nowrap; }
      table.grid tbody tr td.one { width: 100px; }
      table.grid tbody tr td.two { width: 200px; }
    </style>
    <table class="grid">
      <tbody>
        <tr>
          <td class="one"><div>One</div></td>
          <td class="two"><div>Two</div></td>
        </tr>
        <tr>
          <td class="one"><div>Another One</div></td>
          <td class="two"><div>Another Two</div></td>
        </tr>
      </tbody>
    </table>
    

    I would love to be able to eliminate the need to add the extra div. I've spend many hours googling this issue but can't find an alternative.

    Is there a way to do what I need without the need to add the extra div? If So, what is it?

    Is there a way of getting the desired result without using tables at all?

  • Stacey Richards
    Stacey Richards over 15 years
    Thanks for the quick response. I've tried using overflow: hidden; white-space: nowrap; in td but it doesn't seem to work cross browser.
  • annakata
    annakata over 15 years
    why would addign naked spans do anything? let alone improve on adding divs?
  • Stacey Richards
    Stacey Richards over 15 years
    wow, thanks for the link and comments. I will stick with what I've got, but am more educated due to your answer. Thanks.
  • Julix
    Julix over 7 years
    link doesn't work anymore, which is why it's customary to post the relevant content here.
  • Asons
    Asons over 5 years
    Given that the specs. does not define it for table cells, it is not recommended to use max-width: stackoverflow.com/questions/8465385/… ... whether one can or not.