类似 Fixed Height and Changing Width for Header (HTML Table) 的类似问题 - 除了我想问:除了使用
而不是空格之外,还有其他方法可以实现这一目标吗?基本上,我想增加表格数据单元格中的文本内容以保持单元格高度固定,而不是增加单元格宽度..
下面是一个最小的 HTML 示例,它在更改浏览器 (Firefox 43) 宽度时的行为如下:
如您所见,无论 CSS 中的 height
/max-height
规范如何,表 td
字段都会增加其高度,同时减少宽度。
我想要发生的是在这种情况下,td
单元格的指定高度 - 和相应的宽度 - 在浏览器宽度改变时保持不变,而改变的是底部滚动条。
有什么办法可以用 CSS 甚至 JS 实现这一点吗?
回应 @tgallimore 的问题:
回应 @Leothelion 的帖子:我想指定
2em
(或者比方说, 2.5em
)的固定高度,是因为我希望它为最多两行文本提供足够的垂直空间。所以我想要实现的是:* 如果单元格中的文本很短(即一个单词),则没有换行,文本为单行,单元格高度为
2.5em
* 如果单元格中的文本很长(一个完整的句子),那么我希望布局能够确定 2.5em
的单元格高度最多可以容纳两行文本;此后它会尝试打破文本,使得两行中的字符数量大致相同(所以现在我们有了一个“段落”;最后它会将单元格的宽度设置为这个新断行的宽度“段落”。换句话说,我想要这样的布局:
...无论我如何缩放浏览器宽度;如果浏览器宽度太小,则只调整水平滚动条。
示例 HTML 代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="../jquery-1.12.3.min.js"></script>
<style type="text/css">
.mytbl,
.mytbl tr th,
.mytbl tr td {
border-style: solid;
border-color: #000;
border-spacing: 0;
border-collapse: collapse;
padding: 4px;
border-width: 1px;
font: 12px helvetica,arial,sans-serif;
}
.mytbl tr td {
height: 2em;
max-height: 2em;
}
.mtytblwrap {
border-width: 1px;
border-color: #000;
padding: 4px;
overflow: auto;
overflow-y: hidden;
}
</style>
<script type="text/javascript">
ondocready = function() {
// placeholder - nothing for now...
}
$(document).ready(ondocready);
</script>
</head>
<body>
<h1>Hello World!</h1>
<div id="wrapper1" class="mtytblwrap">
<table id="table1" class="mytbl">
<thead>
<tr>
<th> Dendrologist </th>
<th> Iciness </th>
<th> JoyfulDistortion </th>
<th> Suburbicarian </th>
<th> Ecballium </th>
<th> AbulicNonviolence </th>
<th> GrowlerTheocracy </th>
<th> Necessitattion </th>
</tr>
</thead>
<tbody>
<tr>
<td> A1 </td>
<td> Just testing some longer content here, so long that it might not fit on a single line </td>
<td> Molybdenum </td>
<td> D1 </td>
<td> Scanty Distensibility </td>
<td> Arithmetical </td>
<td> G1 </td>
<td> Hypallelomorph </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
最佳答案
你能给 table 一个固定的宽度吗?
您知道您希望每个单元格保持多宽吗?这个宽度可以给每个单元格吗?
如果内容不适合,表格单元格将始终扩展其高度,无论您是否设置高度(因此在这种情况下 height
将用作 min-height
)。
此外,您可能需要使用 .mytbl { table-layout: fixed; }
。这会告诉表格使用您定义的宽度,而不是尝试修复每个单元格中的内容。有关更多信息,请参见:https://css-tricks.com/fixing-tables-long-strings/
关于html - 增加固定高度 HTML 表格数据单元格的宽度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36765375/