如何使表格单元缩小宽度以仅适合其内容?

the*_*cat 18 html css css-tables

我希望表格的宽度为100%,但只有一列可以有一个自由宽度,如:

| A | B | C                                                                  |
Run Code Online (Sandbox Code Playgroud)

因此A和B列的宽度应与其内容的宽度相匹配,但C的宽度应该一直持续到表格结束.

好吧我可以指定A和B的宽度(以像素为单位),但问题是这些列的内容宽度不固定,所以如果我设置一个固定的宽度,它将完全不匹配内容:(

PS:我没有使用实际的表项,而是包含在div中的DL列表.div有display:table,dl有display:table-row,dt/dd display:table-cell ...

Roi*_*mer 25

如果我理解你,你有表格数据,但你想使用div元素在浏览器中呈现它(AFAIK表和div与display:table的行为大致相同).

(这是一个工作的jsfiddle:http://jsfiddle.net/roimergarcia/CWKRA/)

标记:

<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>?
Run Code Online (Sandbox Code Playgroud)

而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 */
}?
Run Code Online (Sandbox Code Playgroud)

可悲的是我一年前无法做到这一点,当我真的需要它时__-!

  • 请注意,在主div中添加`table-layout:fixed`会破坏这个css. (7认同)
  • `white-space:nowrap`可能会更好.如果你在一个单元格中有一个内联的ul列表,那么'pre`选项会导致堆叠 - 至少在一个真实的表标签中. (2认同)