Dynamically set the width of the column headings based on the text inside it
I am creating a table as shown below
Column widths are now constant. There is a link to my code here. We can see that the second column is taking up more space than required.
My question is that we can control the width of a column based on its content while keeping the current table setting where the table headers are tilted.
* {
box-sixing: border-box;
}
.outerDiv {
// background: grey;
height: 200px;
width: 100px;
border: 1px solid black;
border-bottom: 0;
border-left: 0;
transform: skew(-30deg) translateX(58%);
}
th:first-child .outerDiv {
border-left: 1px solid black;
position: relative;
}
.innerDiv {
position: absolute;
width: 220px;
height: 85px;
bottom: -34%;
left: 10px;
transform: skew(30deg) rotate(-60deg);
transform-origin: 0 0;
text-align: left;
}
body,
html {
height: 100%;
}
body {
display: flex;
justify-content: center;
}
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
}
<table cellpadding="0" cellspacing="0">
<tr>
<th>
<div class="outerDiv">
<div class="innerDiv"></div>
</div>
</th>
<th>
<div class="outerDiv">
<div class="innerDiv">First column header cell is very long </div>
</div>
</th>
<th>
<div class="outerDiv">
<div class="innerDiv">Second column</div>
</div>
</th>
<th>
<div class="outerDiv">
<div class="innerDiv">Third column header cell is very very very very long</div>
</div>
</th>
</tr>
<tr>
<td class="wider">Target</td>
<td>5</td>
<td>26</td>
<td>9</td>
</tr>
<tr>
<td class="wider">75th Percentile</td>
<td>5</td>
<td>26</td>
<td>9</td>
</tr>
<tr>
<td class="wider">50th Percentile</td>
<td>5</td>
<td>26</td>
<td>9</td>
</tr>
<tr>
<td class="wider">25th Percentile</td>
<td>5</td>
<td>26</td>
<td>9</td>
</tr>
</table>
+3
source to share
1 answer
You can use display: grid
and use grid-auto-columns
or grid-auto-rows
with min-content
value:
https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-columns
0
source to share