【问题标题】:Fixed table layout with auto width具有自动宽度的固定表格布局
【发布时间】:2017-01-23 07:05:06
【问题描述】:

根据规范,固定表格布局不适用于将width 设置为auto

17.5.2.1 固定表格布局

使用这种(快速)算法,表格的水平布局不会 不依赖于单元格的内容;它只取决于 表格的宽度、列的宽度以及边框或单元格间距。

表格的宽度可以用'width'显式指定 财产。 'auto' 的值(对于 'display: table' 和 'display: inline-table') 表示使用自动表格布局算法。 但是,如果表是块级表('display:table') 正常流程,UA 可以(但不必)......

是否有任何 hack 让它正常工作(使用 纯 CSS)?

我所拥有的:table-layout: fixedwidth: auto 无效:

table{
  /* those two won't work togheter */
  table-layout: fixed;
  width: auto;
}

td{
  /* pure visual purpose */
  border: 1px solid black;
  padding: 10px;
}
<table>
	<tr>
		<td>Mid long text</td>
		<td>The very longest text</td>
		<td>Short</td>
	</tr>
</table>

我想要得到:所有表格单元格的宽度都设置为最宽的:

// width of widest table cell (in px)
var max = 0;

// get width of widest table cell (in px)
$('table td').each(function(){
	max = Math.max(max, $(this).width());
});

// set width of all cells to the width of widest one
$('table td').each(function(){
	$(this).css('width', max +'px');
});
table{
  /* those two won't work togheter */
  table-layout: fixed;
  width: auto;
}

td{
  /* pure visual purpose */
  border: 1px solid black;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
	<tr>
		<td>Mid long text</td>
		<td>The very longest text</td>
		<td>Short</td>
	</tr>
</table>

【问题讨论】:

    标签: css


    【解决方案1】:

    只需为td 分配一个百分比宽度 - 然后您就不需要table 本身的任何 CSS 规则(参见 sn-p)

    .container {
      background-color: #0fa;
      }
    table {
      background-color: #fa0;
      }
    td{
      border: 1px solid black;
      padding: 10px;
      width: 33%;
    }
    <div class="container">
    <table>
    	<tr>
    		<td>Mid long text</td>
    		<td>The very longest text</td>
    		<td>Short</td>
    	</tr>
    </table>
      </div>

    【讨论】:

    • 我希望表格单元格获得最宽的宽度,而不是固定宽度。
    • 然后将 td 宽度设为 33%
    • Johannes 我不希望表格获得与其父容器相关的宽度。
    • 它没有:我将我的 sn-p 更改为 TD 的 33% 宽度。我还为表格和容器添加了背景颜色 - 在那里您可以看到表格或 td 宽度与容器无关(否则表格几乎会填满容器的宽度)。
    • 这看起来很理想。它当然不是动态的,但它似乎满足了 OP 的要求。
    猜你喜欢
    • 1970-01-01
    • 2014-04-17
    • 2017-07-15
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多