2015-11-02 147 views
3

我有一個寬度爲100%的表格,我如何根據文本長度自動調整寬度來設置TD和TR?我使用寬度:自動但它不起作用。這裏是我的代碼:如何使表td tr自動寬度基於文本長度?

.hoverTable { 
 
    width: 100%; 
 
    border-collapse: collapse; 
 
} 
 
.hoverTable td { 
 
    padding: 7px; 
 
    border: #4e95f4 1px solid; 
 
} 
 
/* Define the default color for all the table rows */ 
 

 
.hoverTable tr { 
 
    background: #b8d1f3; 
 
} 
 
/* Define the hover highlight color for the table row */ 
 

 
.hoverTable tr:hover { 
 
    background-color: #ffff99; 
 
} 
 
.hoverTable th { 
 
    background: #b8d1f3; 
 
}
<table class="hoverTable"> 
 
    <tr> 
 
    <th colspan="3">Some Text here</th> 
 
    </tr> 
 
    <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';"> 
 
    <td>This is text length example and text</td> 
 
    <td>Item 1B</td> 
 
    <td>Item 1C</td> 
 
    </tr> 
 
    <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';"> 
 
    <td>Item 2A</td> 
 
    <td>Item 2B</td> 
 
    <td>Item 2C</td> 
 
    </tr> 
 

 
    <th colspan="3" class="width: 100%;">Some Text here</th> 
 

 
    <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';"> 
 
    <td>Item 3A</td> 
 
    <td>Item 3B</td> 
 
    <td>Item 3C</td> 
 
    </tr> 
 
    <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';"> 
 
    <td>Item 4A</td> 
 
    <td>Item 4B</td> 
 
    <td>Item 4C</td> 
 
    </tr> 
 
    <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';"> 
 
    <td>Item 5A</td> 
 
    <td>Item 5B</td> 
 
    <td>Item 5C</td> 
 
    </tr> 
 
</table>

正如你可以在看到這是文本長度例如,寬度不是基於文本長度的文本,我怎麼可以設置寬度基於文本的長度..

我是指基於文本長度的自動寬度?

謝謝

+0

這是一個有點不清楚你想達到的目標。所以你想要一個寬度爲100%的表格,但每個列的寬度都會根據其文本內容進行調整?在某個點上,一個或多個列需要填補空白,以便表格填充其父項的100%。 – ghybs

回答

3

使用以下:

.hoverTable { 
    border-collapse: collapse; 
} 

所以只是刪除width: 100%;,它會工作。該表現在將動態呈現。

小提琴:Click

+0

'table-layout:fixed'與它沒什麼關係,你刪除了'width:100%'。固定佈局甚至可能與佈局混亂,請閱讀更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout – LGSon