Reputation: 23
I have a table that spans most of the page. The width is calc(100% - 20px)
.
When I drag the window really large, the table adjusts so that it occupies the whole window.
When I shrink the window smaller, it again adjusts so that it occupies the whole window BUT at a certain point it stops adjusting and overflows beyond the edge of the window.
I am wondering how I can calculate that "smallest allowed width" of the table in JS or jQuery, without actually changing the size of my window and then doing a $('table').width()
or something similar. Worth noting is that this "smallest allowed width" is variable depending on the content of the table. I've search a fair bit and haven't found any good answers.
/*table style*/
table#myTableId{
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}
Upvotes: 2
Views: 167
Reputation: 18908
You can set a very small width on the table temporarily and check the live width at that moment using getBoundingClientRect
.
const table = document.getElementById('myTableId');
// get the original width in case it was set
const originalWidth = table.style.width;
// set the table's width to 1px (0 does not work)
table.style.width = '1px';
// get the current width
const smallestWidth = table.getBoundingClientRect().width;
// set the original width back
table.style.width = originalWidth;
console.log(smallestWidth);
table#myTableId {
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}
<table id="myTableId">
<tr>
<td>Table Cell Content</td>
</tr>
</table>
Upvotes: 2