Search code examples
htmlcsshtml-tablewhitespacecentering

Display table removes whitespace between inline elements in Chrome, but not in Firefox


Sample code

div {
  display: table;
  margin: 1em auto;
  background: lightBlue;
}
<div id="container">
  <label for="input">label</label>
  <input type="text" id="input">
  <span>span</span>
  <ol>
    <li>text</li>
    <li>text</li>
    <li>text</li>
  </ol>
</div>

This is how I centered the div: Chrome shrinks the container, and sequences of white space between the inline elements are collapsed, but Firefox doesn't remove the whitespace between the label, input and span.

  • Which behavior is correct?
  • What's a cross-browser solution?
  • What's the right approach to center the container?

Solution

    • Which behavior is correct?

    display:table should mean that the entire div's content's should be wrapped in a table, table-row and table-cell. The table-cell establishes a block formatting context for that content, and the elements should layout as normal within that context. So the white space should not be collapsed, and Firefox's behaviour is correct.

    • What's a cross-browser solution?
    • What's the right approach to center the container?

    Assuming you are just using the display:table just to get the shrink-to-fit behaviour to centre the content, and that you only need support for current browsers, the simplest approach is to use width:fit-content instead. Other approaches are possible for older browsers, but you might need additional container elements.

    div {
      width: fit-content;
      margin: 1em auto;
      background: lightBlue;
    }
    <div id="container">
      <label for="input">label</label>
      <input type="text" id="input">
      <span>span</span>
      <ol>
        <li>text</li>
        <li>text</li>
        <li>text</li>
      </ol>
    </div>