Thom Smith Thom Smith - 6 months ago 43
CSS Question

display:table-cell not working on button element

I'm trying to style a sort of command bar. It must work in IE9, so flexbox is out. Instead, I'm using a

display:table
layout.

The first snippet (using
<span>
s) is how I'd like it to look. The second snippet is the proper HTML, and it isn't styled right. The elements are not laid out correctly, which pushes the second button down a line, and the borders do not collapse.

Is there any way to fix this without wrapping the buttons? If I did that, I'd have to undo and redo a lot of styles in order to put the border on the wrapper. If all else fails, I suppose I can replace
<button>
with
<span role="button" tabindex="0">
everywhere.



html {
font-size: 24px;
line-height: 1rem;
}
* {
font: 18px Calibri;
box-sizing: border-box;
}
.controls {
margin: 1rem;
height: 1rem;
width: 800px;
border: 1px solid #c77;
background-color: #eee;
display: table;
border-collapse: collapse;
}
.controls > * {
display: table-cell;
white-space: nowrap;
}
.spacer {
width: 99%;
}
button,
span {
height: 1rem;
border: 1px solid #7c7;
padding: 0 0.5rem;
background: #f7f7f7;
}

<div class="controls">
<div>Title</div>
<div class="spacer"></div>
<span>Button A</span>
<span>Button B</span>
</div>

<div class="controls">
<div>Title</div>
<div class="spacer"></div>
<button type="button">Button A</button>
<button type="button">Button B</button>
</div>




Answer

The problem is that the <button> element cannot accept changes to the display property.

Certain HTML elements, by design, do not accept display changes. Three of these elements are:

  • <button>
  • <fieldset>
  • <legend>

The idea is to maintain a level of common sense when styling HTML elements. For instance, the rule prevents authors from turning a fieldset into a table.

However, there is an easy workaround in this case:

Solution 1: Wrap each button in a div element.

OR

Solution 2: Use another element to submit the form data.

Note that some browser versions may actually accept a display change on a button. However, the solutions above are reliable cross-browser.

References: