csshtml-tablewidthoverflow

Table overflows parent div when td content is too wide


I prepared a JSFiddle to explain/show you my problem: http://jsfiddle.net/nz96C/

It looks alright at first, but when I add some text to #firsttd the whole table overflows the parent div once the tds whole width is used. I know how to solve this problem with CSS (#firstdiv {width:90px;overflow:hidden;}) but I don't know the exact number of pixels (percentage doesn't work). Also I don't want the text in the first td to wrap.

I hope you get my problem, I even have trouble explaining it in my first language.

EDIT: My goal is to have a table in which it doesn't matter how long the text in the first td is, the table should never overflow the parent div - without the text being wrapped. I want the text which overflows the first td just not to be shown.


Solution

  • Same answer as another very recent topic:table-layout:fixed; + width. DEMO

    table {
        table-layout:fixed;
        width:100%;
    }
    td {
        border: 1px solid black;
        overflow:hidden;/* optionnal*/
    }
    #firsttd {
        white-space: nowrap;
    }
    

    edit : about comment below :

    @MatthieuRiegler

    table-layout:fixed; is bad if you want cell with different width.

    This is your own opinion without any explanation

    here is a demo where table-layout and cell's width can be different:

    table {
      width: 100%;
      table-layout: fixed;
    }
    
    table,
    td,
    th {
      border: 1px solid;
    }
    
    thead tr th:nth-child(1) {
      width: 5em;
    }
    
    thead tr th:nth-child(2) {
      width: 20%;
    }
    
    thead tr th:nth-child(3) {
      width: 7.5em;
    }
    <table>
      <thead>
        <tr>
          <th>Head Cell</th>
          <th>Head Cell</th>
          <th>Head Cell</th>
          <th>Head Cell</th>
          <th>Head-Cell-Text</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
        </tr>
        <tr>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
        </tr>
        <tr>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
        </tr>
        <tr>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
        </tr>
        <tr>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
          <td>Cell</td>
        </tr>
      </tbody>
    </table>

    width + table-layout:fixed might just be a bad idea if no responsiveness is thought aside.