[英]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> <button onclick='doTable(array3)'>Table for 2</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.