Skip to content

Instantly share code, notes, and snippets.

@zelaznik
Created May 16, 2023 19:05
Show Gist options
  • Save zelaznik/42c49933cd99c6b30cea4df0f25aee25 to your computer and use it in GitHub Desktop.
Save zelaznik/42c49933cd99c6b30cea4df0f25aee25 to your computer and use it in GitHub Desktop.
Javascript Code To Make Sure Table Column Widths Are Consistent
function equalize_widths(table) {
var col_count = [...table.querySelectorAll('thead > tr > th')].length;
var total_table_width = 0;
for (let i=0; i<col_count; i++) {
let elements = [...table.querySelectorAll(`thead > tr > th:nth-child(${i+1}), tbody > tr > td:nth-child(${i+1})`)];
let max_column_width = elements.reduce(function(acc, el) {
let computedStyle = window.getComputedStyle(el);
let extraSpacing = parseFloat(computedStyle.getPropertyValue('padding-right')) +
parseFloat(computedStyle.getPropertyValue('padding-left')) +
parseFloat(computedStyle.getPropertyValue('margin-right')) +
parseFloat(computedStyle.getPropertyValue('margin-left')) +
parseFloat(computedStyle.getPropertyValue('border-right-width')) +
parseFloat(computedStyle.getPropertyValue('border-left-width'));
let totalWidth = Math.max(el.offsetWidth, el.scrollWidth) + extraSpacing;
return Math.max(acc, totalWidth);
}, 0);
total_table_width += max_column_width;
elements.forEach(function(el) {
el.style.minWidth = `${max_column_width}px`;
});
}
table.style.width = `${total_table_width}px`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment