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

Time:01-23

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?

CodePudding user response:

  • 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>

CodePudding user response:

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

try:

div {
  display: table;
  margin: 1em auto;
  background: lightBlue;
  width: 50%;
  left: 25%;
  position: absolute;
}

You can change the Width of the element but be sure to change the left offset as well. for exemple if the width = 30% then the left offset should be:

(100 - 30) / 2

  • Related