簡體   English   中英

如果表只有一行,則 HTML 表中的列寬變化

[英]Column width changes in HTML table if the table only has a single row

我有一個一維對象數組。 我需要在具有 3 列的表中顯示該數組中的數據。 我為每列分配1/3rd of 100% width ,因為列數是固定的。 如果我要顯示 3 個或更多對象,則一切正常。 但是,如果我有 1 或 2 個對象,則列寬會發生變化,列會擴展以適應最大寬度。

是我的代碼。 我知道到處都有內聯 css,這是故意的。 請多多包涵。 我提供了一個包含 2 個對象的數組和另一個包含 4 個對象的數組,這樣您就可以看出差異。 我知道我可以為不寫一個單獨的條件。 對象小於 3,然后設置特定寬度,但我希望這可以單獨使用 CSS 解決。 如果有人可以提供幫助,我將不勝感激。

編輯:我已經有一個基於 JS 的解決方案。 如果數組的對象少於 3 個,我會動態計算表格寬度,如下所示。

let width = '100%';
if (listOfPeople.length < 3 && listOfPeople.length > 0) {
  width = (listOfPeople.length * 100) / 3 + '%';
}

而那個寬度就是這樣使用的

appDiv.innerHTML = `
    <table width="${width}" border="0">
        <tbody>
            <td style="width: calc(100% / 3); height: 100%; max-width: calc(100% / 3); padding: 10px;">
              data
            </td>
        </tbody>
    </table>
  `;

我沒有在鏈接代碼中更新此解決方案,因為我真的希望有一個 CSS 解決方案。 如果有人有任何想法,請告訴我

我在這里添加了 2 個變量。 iterator僅根據剩余的 listOfPeople 計算任何給定行的 TD 數量,而perc計算行的寬度。

 const array2 = [ new Map([ ['name', 'Jacqueline M. Goodrich'], ['img', ''], ['department', 'Marketing'], ['location', 'jhvjb'] ]), new Map([ ['name', 'Jacqueline M. Goodrich2'], ['img', ''], ['department', 'Marketing'], ['location', 'frds'] ]), new Map([ ['name', 'Jacqueline M. Goodrich2'], ['img', ''], ['department', 'Marketing'], ['location', 'frds'] ]), new Map([ ['name', 'Jacqueline M. Goodrich2'], ['img', ''], ['department', 'Marketing'], ['location', 'frds'] ]) ]; const array3 = [ new Map([ ['name', 'Jacqueline M. Goodrich'], ['img', ''], ['department', 'Marketing'], ['location', 'jhvjb'] ]), new Map([ ['name', 'Jacqueline M. Goodrich2'], ['img', ''], ['department', 'Marketing'], ['location', 'frds'] ]) ] function doTable(listOfPeople) { let cardsrows = ''; for (let i = 0; i < listOfPeople.length;) { let cards = ''; let iterator = Math.min((listOfPeople.length - i), 3) let perc = Math.min(listOfPeople.length, 3) for (let col = 0; col < iterator; col++) { const record = listOfPeople[i]; const card = `<td style="border:1px solid #ccc; width: calc(100% / ${perc}); height: 100%; max-width: calc(100% / ${perc}); padding: 10px;">info</td>`; cards = cards.concat(card); i++; } const row = cards? `<tr>` + cards + `</tr>`: ``; cardsrows = cardsrows.concat(row); } document.getElementById('appDiv').innerHTML = ` <table width="100%" border="0"> <tbody> ${cardsrows} </tbody> </table> `; }
 <div id='appDiv'></div> <button onclick='doTable(array2)'>Table for 4</button> &nbsp; <button onclick='doTable(array3)'>Table for 2</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM