How to make a table cell shrink width to fit only its contents?

时间秒杀一切 提交于 2019-12-03 15:16:43

问题


I want the table to have 100% width, but only one column from it should have a free width, like:

| A | B | C                                                                  |

so the width of A and B columns should match the width of their contents, but the width of C should go on until the table ends.

Ok I could specify the width of of A and B in pixels, but the problem is that the width of the contents of these columns is not fixed, so if I set a fixed width it wouldn't match the contents perfectly :(

PS: I'm not using actual table items, but a DL list wrapped in a div. The div has display:table, dl has display:table-row, and dt/dd display:table-cell ...


回答1:


If I understood you, you have tabular data but you want to present it in the browser using div elements (AFAIK tables and divs with display:table behaves mostly the same).

(here is a working jsfiddle: http://jsfiddle.net/roimergarcia/CWKRA/)

The markup:

<div class='theTable'>
    <div class='theRow'>
        <div class='theCell' >first</div>
        <div class='theCell' >test</div>
        <div class='theCell bigCell'>this is long</div>
    </div>
    <div class='theRow'>
        <div class='theCell'>2nd</div>
        <div class='theCell'>more test</div>
        <div class='theCell'>it is still long</div>
    </div>
</div>​

And the CSS:

.theTable{
    display:table; 
    width:95%; /* or whatever width for your table*/
}
.theRow{display:table-row}
.theCell{
    display:table-cell;
    padding: 0px 2px; /* just some padding, if needed*/
    white-space: pre; /* this will avoid line breaks*/
}
.bigCell{
    width:100%; /* this will shrink other cells */
}​

The sad part is I couldn't do this one year ago, when I really needed it -_-!



来源:https://stackoverflow.com/questions/14084221/how-to-make-a-table-cell-shrink-width-to-fit-only-its-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!