display:table-cell not working on button element

徘徊边缘 提交于 2019-12-02 00:07:06

问题


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>

回答1:


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:

  • Bug 984869 - display: flex doesn't work for button elements
  • Bug 1176786 - Flexbox on a blockifies the contents but doesn't establish a flex formatting context


来源:https://stackoverflow.com/questions/37444481/displaytable-cell-not-working-on-button-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!