HTML Element Style How to - Center content with div table layout








Question

We would like to know how to center content with div table layout.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.heading {<!--   w w  w . j  ava2s  .  c  om-->
  text-align: center;
  display: table;
  margin: 30px 0;
}

.lines {
  display: table-cell;
  width: 48%; /* the exact value is not that critical... */
  border-top: 1px solid #2c2c2c;
  border-bottom: 1px solid #2c2c2c;
}

.heading-link {
  display: table-cell;
  white-space: nowrap; /* keeps the text from wrapping... */
  padding: 10px 20px;
}
</style>
</head>
<body>
  <div class='heading'>
    <div class='lines'></div>
    <div class='heading-link'>
      <a href=''>Link Text</a>
    </div>
    <div class='lines'></div>
  </div>
  <div class='heading'>
    <div class='lines'></div>
    <div class='heading-link'>
      <a href=''>Really Long Link Text that is still centered</a>
    </div>
    <div class='lines'></div>
  </div>
</body>
</html>

The code above is rendered as follows: