【问题标题】:Fill up a table cell completely with any number of equally wide buttons in CSS用 CSS 中任意数量的等宽按钮完全填充表格单元格
【发布时间】:2017-09-06 00:03:59
【问题描述】:

我有一个这样的(简化的)HTML 结构:

<div class="table">
    <form class="tr">
        <span class="td">
            <input type="submit" value="Button 1"/>
            <input type="submit" value="Button 2"/>
            <input type="submit" value="Button 3"/>
        </span>
    </form>
</div>

里面的提交按钮是用JSP在服务器端动态生成的,所以它们的数量可能会有所不同,通常在1-3的范围内。

这是我目前所拥有的简化 CSS:

.table {
    display: table;
}
.table .tr {
    display: table-row;
}
.table .tr .td {
    display: table-cell;
    padding: 5px;
    border: 1px solid black;
}
.table .tr .td input[type=submit] {
    width: 100%;
}

但是,设置按钮的width=100% 会使每个按钮与单元格一样宽,从而导致它们垂直环绕并彼此相邻显示。

我想要的是扩展所有按钮的宽度,以便它们填满包含的单元格,但一个单元格中的所有按钮都应具有相同的宽度。这必须适用于每个单元格的不同数量的按钮,我想要一个不依赖 JavaScript 的解决方案。

这是我希望它的外观的另一个可视化:

+----------------------------------------------+
| [  Button 1  ] [     B2     ] [   Btn. 3   ] |
+----------------------------------------------+
| [      Button A      ] [      Button B     ] |
+----------------------------------------------+
| [           only one wide button           ] |
+----------------------------------------------+

【问题讨论】:

  • 每行MAX多少?
  • @AllDani 正如我所说,通常在 1-3 范围内。不确定我将来是否需要添加更多内容。
  • Flexbox 是唯一想到的,但 JavaScript 具有更好的跨浏览器兼容性和支持:caniuse.com/#feat=flexbox VS caniuse.com/#search=javascript

标签: html css flexbox width


【解决方案1】:

这是flexbox 的完美案例- 将display: flex 应用于您的td

.table .tr .td {
  display: flex;
} 

让我知道您对此的反馈。谢谢!

.table {
  display: table;
}
.table .tr {
  display: table-row;
}
.table .tr .td {
  display: flex;
  padding: 5px;
  border: 1px solid black;
}
.table .tr .td input[type=submit] {
  width: 100%;
}
<div class="table">
  <form class="tr">
    <span class="td">
            <input type="submit" value="Button 1"/>
            <input type="submit" value="Button 2"/>
            <input type="submit" value="Button 3"/>
        </span>
    <span class="td">
            <input type="submit" value="Button 1"/>
            <input type="submit" value="Button 2"/>
        </span>
    <span class="td">
            <input type="submit" value="Button 1"/>
        </span> 
  </form>
</div>

【讨论】:

  • 您的解决方案没有直接起作用,因为我需要我的.td 元素具有display:table-cell,否则所有单元格都会垂直对齐而不是行和列。但是,你让我走上了正确的道路。我现在将每个 .td 元素的内容包装在 &lt;span style="display:flex"&gt;...&lt;/span&gt; 中,而不是直接更改 .td 元素的 display 样式。现在按预期工作。
猜你喜欢
  • 2012-06-22
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2013-05-26
  • 2012-03-19
相关资源
最近更新 更多