2016-11-22 195 views
0

我想動態地將寬度添加到td,它在Chrome和Safari中正常工作,但在FF中無法正常工作。CSS - calc無法正常工作Firefox

Fiddle

HTML

<table border="0" cellspacing="0" cellpadding="0"> 
    <tr> 
     <td>1</td> 
     <td>Title</td> 
     <td>Interpret</td> 
     <td>Album</td> 
     <td>Year</td> 
     <td>YouTube</td> 
    </tr> 
</table> 

CSS

table{ 
    table-layout:fixed; 
    width: 100%; 
    border-collapse: collapse; 
} 
td{ 
    border:1px solid red; 
} 
td:first-child{ 
    width: calc(100%/6 * 0.5); 
} 
td:last-child{ 
    width: calc(100%/6 * 2); 
} 

如果我硬編碼的像素值,而不是爲100%例如,calc(690px/6 * 2),它的工作原理。

+3

您將有Flexbox的更好的運氣。 – 2016-11-22 14:39:21

回答

0

刪除此行的CSS:

table { 
    // table-layout: fixed; 
    width: 100%; 
    border-collapse: collapse; 
} 

table-layout: fixed使您能夠將自己的寬度適用於表。我不知道爲什麼Firefox不配合這個規定。

參考: using calc() with tables

+0

@Turnip哦?我從參考線索的頂部投票答案中讀到它。我會調整它。謝謝! – Roberrrt

+0

同意!但固定佈局提供了與所有'td'相等的寬度,並且在內容大小變化時不會改變。 – moustacheman

-1

爲了這個工作,據我所知,在試圖模擬一個固定的單元寬度是將table-layoutfixedauto改變以及設置一個默認的寬度全部爲td

要動態地做到這一點,我們將表格寬度除以列數(在這種情況下,以百分比表示) - 100/6 = 16.66666...

然後我們使用calc()內的值:first-child:last-child,通過用16.6666%替換100%同時也保持現有的改性劑(0.52,分別地)。

CSS

table{ 
    table-layout:auto; 
    width: 100%; 
    border-collapse: collapse; 
} 
td{ 

    border:1px solid red; 
    width: 16.6666%; 
} 
td:first-child{ 
    width: calc(16.6666% * 0.5); 
} 
td:last-child{ 
    width: calc(16.6666% * 2); 
} 

Example Fiddle

+0

您不需要手動分割它,它會在您將'table-layout'更改爲'auto'時起作用。 – moustacheman

+0

@aravindtrue爲了使它在Firefox中工作,根據OP的請求,有必要手動完成它,否則第一個和最後一個之間的所有列都會有不同的寬度。通過使這些列流暢且均勻,明確地解決這個問題,同時仍然允許第一個和最後一個是明確的(通過百分比*修飾符)。 – seantunwin