I would like to create a table with not fixed width.
The width depends on the text length inside.
But later I would like to create another table with the same width.
It is possible?
I would like to create a table with not fixed width.
The width depends on the text length inside.
But later I would like to create another table with the same width.
It is possible?
: copying the first table's rendered width to a second is fine — the key is to measure the actual laid-out width after the browser finishes layout, then apply that pixel value to the other table. was right that JavaScript can do this; the one-liner in post #4 used innerWidth (which is a window property, not an element property). Use the element measurement APIs instead.
A practical pattern: wait until layout is done, read the first table's width with getBoundingClientRect() (or offsetWidth) and write that value as a pixel width on the second table. Re-run on resize if the layout can change. Example:
document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementById('table1');
var b = document.getElementById('table2');
if (!a || !b) return;
function match() {
var w = a.getBoundingClientRect().width;
b.style.width = Math.round(w) + 'px';
}
match();
window.addEventListener('resize', match);
}); Notes and troubleshooting:
getBoundingClientRect() gives sub-pixel accuracy; offsetWidth gives an integer and includes borders. See MDN: Element.getBoundingClientRect and HTMLElement.offsetWidth.box-sizing, padding, or borders, set them consistently (or copy the computed boxSizing) so the visual widths match.table-layout: fixed and explicit column widths (via colgroup) rather than copying a final pixel width.Jump to Post— twiss 155You could try to put them both in a div, with the div's width:auto, and the tables a maximum width. Or you could the width of the second table to the width of the first table with javascript (onload).
You could try to put them both in a div, with the div's width:auto, and the tables a maximum width. Or you could the width of the second table to the width of the first table with javascript (onload).
How to do this second one ?
Give them both and id:
document.getElementById('id2').style.width = document.getElementById('id1').innerWidth + 'px'; Or something like that - not tested.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.