首页 > 解决方案 > 是否可以使表格的前两列与其内容一样宽,而第三列占据剩余空间?

问题描述

仍然无法制作合适的聊天框;/

我的要求很简单:第一列是时间戳,第二列是海报的昵称,最后一列是消息内容。因此: 前两列应该占用尽可能多的空间以避免换行,但不要更多以避免浪费空间;而第 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吗?

标签: csshtml-tablewidthcolumn-width

解决方案


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>


推荐阅读