macu
macu

Reputation: 379

Text wrap in table with fill-remaining-width middle column

I am trying to get a horizontal line to stretch between the first and last columns in a table but I need the first and last columns to wrap if the text is long. The only way I have found to get the desired effect is to use width:100%; on the middle column, and white-space:nowrap; on the first and last, but I need to find another way as I need the text to wrap when there isn't enough space. Is there a way to achieve this effect in plain CSS?

https://jsfiddle.net/macu/8axk5qv5/4/

table {
  width: 100%;
}

td {
  vertical-align: middle;
  white-space: nowrap;
}

td:nth-child(2) {
  width: 100%;
}

.line {
  border-top: thin solid blue;
}
<table>
  <tr>
    <td>Title cell with a long title that should wrap</td>
    <td><div class="line"></div></td>
    <td>Another cell, should wrap</td>
  </tr>
</table>

If the text is long enough there should be no line, and the text should wrap normally: showing wrapping text

Upvotes: 0

Views: 423

Answers (2)

Stickers
Stickers

Reputation: 78716

You can put a span or div in each cell, and make them to use white background, then set the line on the table row to create such layout visually.

Check out the fiddle demos below, so you can easily resize and see the wrapping text.

jsFiddle

.table {
  width: 100%;
  border-collapse: collapse;
}

.table tr {
  background: linear-gradient(blue, blue) center/99.99% 1px no-repeat;
}

.table div {
  background: white;
  display: inline-block;
}

.middle div {
  min-width: 100px; /*remove or adjust value as need*/
}

.last {
  text-align: right;
}
<table class="table">
  <tr>
    <td class="first">
      <div>Title cell with a long title that should wrap</div>
    </td>
    <td class="middle">
      <div><!-- This td can be removed if no min-width needed --></div>
    </td>
    <td class="last">
      <div>Another cell, should wrap</div>
    </td>
  </tr>
</table>

But using flexbox can make it much easier, if you don't have to use table.

jsFiddle

.container {
  display: flex;
}

.line {
  background: linear-gradient(blue, blue) center/1px 1px repeat-x;
  flex: 1;
  min-width: 100px; /*remove or adjust value as need*/
}
<div class="container">
  <div>Title cell with a long title that should wrap</div>
  <div class="line"></div>
  <div>Another cell, should wrap</div>
</div>

Upvotes: 2

adnan tariq
adnan tariq

Reputation: 197

try by removing the white-space: nowrap; on the TD tag, then target the first and the third TD with

td {
vertical-align: middle;
//white-space: nowrap;
}
td:nth-child(1),td:nth-child(3) {
//add whatever min-width AND max-width so it could be something like this
min-width:150px;
max-width:300px;
}

see if that helps.

Upvotes: -1

Related Questions