Imagine this scenario:
I have a main element with a max-width
of 800px
, utilizing the available space by using
flex: 1;
Now, I want to place a child table within this element, and I want it to overflow when the parent element shrinks. In other words, I want the table's max-width
to match the current width of the parent element.
To summarize, the structure looks like this:
<main style="max-width: 800px; flex: 1;">
<article style="width: 100%; max-width: 100%;">
<!-- more elements wrapping the table, all set to 100% width & max-width -->
<table style="overflow-x: scroll; width: 100%; max-width: 100%;"></table>
</article>
</main>
This setup doesn't achieve the desired result. Instead of overflowing at the current width of the main
component, the table expands to 800px before overflowing.
How can this issue be resolved?
Below is a simple code snippet showcasing the problem:
body {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
background: red;
}
main {
flex: 1;
width: 100%;
max-width: 800px;
background: white;
}
article {
width: 100%;
max-width: 100%;
}
div {
width: 100%;
max-width: 100%;
overflow-x: scroll;
}
table,
tbody {
max-width: 100%;
background: green;
width: 100%;
}
td {
white-space: nowrap;
}
<html>
<body>
<h1>
The main component should shrink below its max width when the window size decreases, causing its children to overflow accordingly. Currently, overflowing children force the parent element to stay at its max width.
</h1>
<main>
<article>
<div>
<table>
<tbody>
<tr>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
<td>
This text demonstrates that it should overflow as intended but instead fills the parent up to its max width (800px).
</td>
</tr>
</tbody>
</table>
</div>
</article>
</main>
</body>
</html>