简体   繁体   中英

Responsive table column with CSS

There's a table with three columns, the first and the last are fixed and the middle one should be fluid.

The problem - inside of the middle column there's text with nowrap and it prevents it from being fluid.

How that could be done?

How it looks on wide page (correct behaviour):

在此输入图像描述

How it should look on narrow page:

在此输入图像描述

How it actually looks on narrow page (incorrect behaviour, see scrollbar):

图片

The code https://jsfiddle.net/8c9msa71/

 td { border: 1px solid black; } .fluid { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } 
 <table> <tr> <td>first</td> <td class="fluid">very-very-very-very-very-very-long-second-text</td> <td>third</td> </tr> </table> 

you can do it by adding a div

 td { border: 1px solid black; } .fluid { position: relative; width: 70%;} .fluid div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; position: absolute; left: 5px; right: 5px; top: 0; } 
 <table width="100%"> <tr> <td>first</td> <td class="fluid"> <div>very-very-very-very-very-very-long-second-text</div> </td> <td>third</td> </tr> </table> 

I noticed the solution to add a div.

If you don't want to or need to add a div, you could use max-width.

Explanation: Your first problem is that none of your elements has a width attribute set. To start with I would set a max-width of your "very-very-long-second-text". For example you can add max-width: 60vw; to your .fluid . If you're not familiar with the vw syntax, read more here: https://www.w3.org/TR/css3-values/#vw

By only adding this, you'll be almost there. You'll still have one problem left: On very small devices / resolutions, you notice that your third table-data, <td></td> will disappear out of visible area.

Instead of collapsing ALL the content, I recommend using display: inline-block; on your table data <td></td> . What this does is that it will display your table data inline as long as they have enough space to be inline. In addition a small part of the information will be visible, instead of the result of NO information visible at all. When the available area becomes smaller (ie resizing the window), they will start jumping down one by one.

Full CSS:

td { 
  border: 1px solid black; 
  display: inline-block;
}

.fluid { 
  max-width: 60vw; 
  white-space: nowrap; 
  overflow: hidden; 
  text-overflow: ellipsis; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM