如何设置表格单元格的最大高度?

新手上路,请多包涵

我有一个固定宽度和高度的表格单元格,如果文本太大,单元格大小应该保持不变,文本应该被溢出隐藏:隐藏。

 div {
   display: table-cell
   height: 100px;
   width: 100px;
   overflow: hidden;
   vertical-align: middle;
}

但是,如果添加的文本过多,表格单元格会扩展到 100 像素以上。有什么技巧可以防止它膨胀吗?

文本长度应为几行,因此“white-space:nowrap”解决方案不适用

原文由 skyisred 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 474
2 个回答

根据 CSS 2.1 规则,表格单元格的高度是“内容所需的最小高度”。 Thus, you need to restrict the height indirectly using inner markup, normally a div element ( <td><div>content</div></td> ), and set height and overflow div 元素上的属性(当然,没有设置 display: table-cell 元素,因为这会使其高度遵守 CSS 2.1 表格单元格规则)。

原文由 Jukka K. Korpela 发布,翻译遵循 CC BY-SA 3.0 许可协议

我不认为接受的答案实际上完全解决了问题。你想在表格单元格内容上有一个 vertical-align: middle 。但是,当您在表格单元格内添加一个 div 并为其指定高度时,该内部 DIV 的内容将位于顶部。检查这个 jsfiddle 。溢出:隐藏;工作正常,但如果您缩短内容使其只有一行,则该行 不会垂直居中

解决方案不是在表格单元格内而是在外部添加 DIV。这是 代码

 /* some wrapper */
div.d0 {
    background: grey;
    width:200px;
    height: 200px;
}

div.table {
    margin: 0 auto; /* just cosmetics */
    width: 150px;
    height: 150px;
    background: #eee;
    display: table;
}

div.tablecell {
    display: table-cell;
    vertical-align: middle;
    text-align:center;
    height: 100%;
    width: 100%;
    background: #aaa;
}

div.outer-div {
    height: 150px;
    overflow: hidden;
}
 <div class="d0">
    <div class="outer-div">
        <div class="table">
            <div class="tablecell">
                Lorem ipsum
                <!--dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,-->
            </div>
        </div>
    </div>
</div>

原文由 beipawel 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题