HTML Element Style How to - Center a table








Question

We would like to know how to center a table.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
table {<!--from  w w  w  .  j  ava2 s .c  o  m-->
  border: 1px solid red;
  width: 100%;
  max-width: 20em;
  margin-right: auto;
  margin-left: auto;
}
</style>
</head>
<body>
  <table>
    <th colspan='3'>header</th>
    <tr>
      <td>data</td>
      <td>data</td>
      <td>data</td>
    </tr>
    <tr>
      <td>data</td>
      <td>data</td>
      <td>data</td>
    </tr>
  </table>
</body>
</html>

The code above is rendered as follows: