是否可以使表格的前两列与其内容一样宽,而第三列占据剩余空间?
Posted
技术标签:
【中文标题】是否可以使表格的前两列与其内容一样宽,而第三列占据剩余空间?【英文标题】:Is it possible to make the first two columns of a table as wide as their content with the third column occupying the remaining space? 【发布时间】:2019-11-19 10:30:59 【问题描述】:仍然无法制作合适的聊天框;/
我的要求很简单:第一列是时间戳,第二列是发帖人的昵称,最后一列是消息内容。因此: 前两列应该占用尽可能多的空间以避免换行,但不要更多以避免浪费空间;而第 3 列应占用剩余空间,但仅此而已,必要时强制换行。
但是,两种表格布局 - auto
和 fixed
- 都失败了。
table-layout: auto;
在前两列中换行,如果输入一个大字作为消息内容,尽管overflow-wrap: break-word
会异常拉伸表格:
.chatbox
display: table;
.message
display: table-row;
.timestamp, .author, .content
display: table-cell;
padding-right: 10px;
.content
overflow-wrap: break-word;
<ul class="chatbox">
<li class="message">
<span class="timestamp">9.07.2019, 17:22:50</span>
<span class="author">Some Longer Nick</span>
<span class="content">I can see linebreaks in the preceeding two columns and I'd like to avoid them.</span>
</li>
<li class="message">
<span class="timestamp">9.07.2019, 17:27:41</span>
<span class="author">Nick</span>
<span class="content">AnAbsurdlyLongWordThatCompletelyAndUtterlyDisruptsTheLayoutOfMyChatbox</span>
</li>
</ul>
table-layout: fixed;
不允许我将前两列设置为取决于其内容的宽度:
body
width: 500px;
.chatbox
display: table;
table-layout: fixed;
width: 100%;
.message
display: table-row;
.timestamp, .author, .content
display: table-cell;
padding-right: 10px;
.content
overflow-wrap: break-word;
<ul class="chatbox">
<li class="message">
<span class="timestamp">9.07.2019, 17:22:50</span>
<span class="author">Nick1</span>
<span class="content">Too much blank space surrounding the timestamp and authors' nicks do not leave enough space for message contents</span>
</li>
<li class="message">
<span class="timestamp">9.07.2019, 17:27:41</span>
<span class="author">Nick2</span>
<span class="content">To some extend I could remedy this by explicitely setting column widths, however, this would obviously not adapt to varying lengths of nicks. Only short nicks talking would again waste space while longer nicks could break</span>
</li>
</ul>
使用display: table
可以做我想做的事吗?
【问题讨论】:
【参考方案1】:与您一起考虑white-space: nowrap;
的第一个解决方案
.chatbox
display: table;
.message
display: table-row;
.timestamp, .author, .content
display: table-cell;
padding-right: 10px;
.timestamp, .author
white-space: nowrap;
.content
overflow-wrap: break-word;
word-break:break-word;
<ul class="chatbox">
<li class="message">
<span class="timestamp">9.07.2019, 17:22:50</span>
<span class="author">Some Longer Nick</span>
<span class="content">I can see linebreaks in the preceeding two columns and I'd like to avoid them.</span>
</li>
<li class="message">
<span class="timestamp">9.07.2019, 17:27:41</span>
<span class="author">Nick</span>
<span class="content">AnAbsurdlyLongWordThatCompletelyAndUtterlyDisruptsTheLayoutOfMyChatbox</span>
</li>
</ul>
【讨论】:
以上是关于是否可以使表格的前两列与其内容一样宽,而第三列占据剩余空间?的主要内容,如果未能解决你的问题,请参考以下文章