2016-04-29 83 views
2

我正在創建一個包含6列的表格。第一列有一行文字,將是最寬的一列。剩下的5列將有文本的標題將被動態加載,所以我不知道寬度。列表大小匹配的html表格

本表採用Bootstrap(v3.3)設計,需要有響應。

有沒有辦法將第一列的大小設置爲設定的大小,然後根據最大的文本值來確定剩餘列的大小,使它們全部具有相同的寬度?

以下是僅顯示標題和第一行的表格。正如你所看到的標題列有不同的寬度。

<table> 
    <thead> 
    <tr> 
     <th></th> 
     <th>Terrible</th> 
     <th>Bad</th> 
     <th>Average</th> 
     <th>Good</th> 
     <th>Excellent</th> 
    </tr> 
    </thead> 
    <tr> 
    <td>How was the food in the hotel</td> 
    <td class="text-center">o</td> 
    <td class="text-center">o</td> 
    <td class="text-center">o</td> 
    <td class="text-center">o</td> 
    <td class="text-center">o</td> 
    </tr> 
</table> 

這裏是一個demo fiddle

回答

2

我希望這是有幫助!

基本上,你可以通過JavaScript來找到最寬的列,(忽略空列)給你最大寬度。然後將列設置爲該寬度。

請參見下面的小提琴:)

jQuery(document).ready(function(){ 
    var largestWidth; 

    jQuery('.table').each(function(index, element){ 
    largestWidth = 0; // Reset the width for every table (presuming we want this to affect every table) 

    jQuery(element).find('th').each(function(innerIndex, innerElement){ 
     console.log(largestWidth); 
     if(jQuery(innerElement).width() > largestWidth && jQuery(innerElement).html() !== ''){ 
     largestWidth = jQuery(innerElement).width(); //Set to new highest width. 
     } 
    }); 

    jQuery(element).find('th:not(:first-child)').width(largestWidth + 'px'); // Set all but first column to highest width. 
    }); 
}); 

https://jsfiddle.net/cetfghz4/4/

+2

雖然這肯定工程,我想知道是否有一個CSS代碼少的代碼解決方案? –

+1

可能有,如果我打算,我會使用'table-layout:fixed',但是左列會出現問題。如果有人知道一個CSS解決方案,它會很有趣。 – Benjamin

+0

我希望有一個CSS解決方案。這是有效的,但第一列包含在調整大小中,但它應占用剩餘的空間。 –

0

你可以使用類似的東西:

<tr> 
    <th class="col-xs-2 col-sm-7"></th> 
    <th class="col-xs-2 col-sm-1">Terrible</th> 
    <th class="col-xs-2 col-sm-1">Bad</th> 
    <th class="col-xs-2 col-sm-1">Average</th> 
    <th class="col-xs-2 col-sm-1">Good</th> 
    <th class="col-xs-2 col-sm-1">Excellent</th> 
</tr> 

demo fiddle

你將不得不放棄更多的努力,使列標題響應(如righ t媒體查詢來垂直放置標題文本),但此解決方案將適用於列寬問題。

有它的自舉機類,你會發現更多的文檔here

我希望它可以幫助

+0

這不會調整最後5列! –

+0

我編輯了我的帖子以添加一些改進(請參閱:https://developer.mozilla.org/fr/docs/Web/CSS/Media_queries)內容將在小屏幕上調整大小。我認爲這是做這些事情的更好方法 – Tony

0

讓它看上方,使用flexbox

<div class="flex-row"> 
    <div class="question">Some question</div> 
    <div class="option">Option</div> 
    <div class="option">Option</div> 
    <div class="option">Option</div> 
    <div class="option">Option</div> 
    <div class="option">Option</div> 
</div> 

.flex-row { 
    display: flex; 
} 

.question { 
    flex: 5; 
} 

.option { 
    flex: 1; 
}