Search code examples
htmlcsshtml-tablewidth

width: auto doesn't work with table inside


I'd like to set the width of the parent (#timer) to auto, but unfortunately the table inside effects the width of this parent and changes it to a 100% width :(.

Here is my code:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
}

html, body {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  -webkit-user-select: none;
  -moz-user-select: -moz-none;
  -ms-user-select: none;
  user-select: none;
}

.time {
  margin: auto;
  border: 1px solid blue;
}

#clock {
  font-family: 'Lato', sans-serif;
  font-weight: 300;
  font-size: 100px;

  border: 1px solid red;

}

table {
  width: 100%;
  table-layout: fixed;
}

td {
  width: calc(100% / 3);
  text-align: center;
}

table, td {
  border: 1px solid #000;
}
<div class="time">
  <h1 id="clock">00 : 00 : 00</h1>
  <table>
    <tr>
      <td>hours</td>
      <td>minutes</td>
      <td>seconds</td>
    </tr>
  </table>
</div>

Thank you for your help and explanations :).

Best regards


Solution

  • Use min-width instead of width for the table:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    html, body {
      height: 100%;
    }
    
    body {
      display: flex;
      flex-direction: column;
      user-select: none;
    }
    
    .time {
      margin: auto;
      border: 1px solid blue;
    }
    
    #clock {
      font-family: 'Lato', sans-serif;
      font-weight: 300;
      font-size: 100px;
    
      border: 1px solid red;
    
    }
    
    table {
      min-width: 100%;
      table-layout: fixed;
    }
    
    td {
      width: calc(100% / 3);
      text-align: center;
    }
    
    table, td {
      border: 1px solid #000;
    }
    <div class="time">
      <h1 id="clock">00 : 00 : 00</h1>
      <table>
        <tr>
          <td>hours</td>
          <td>minutes</td>
          <td>seconds</td>
        </tr>
      </table>
    </div>