Original Solution:
To solve the issue of the fixed height, you can add overflow: scroll
to the outermost <div>
. This will allow for scrolling when the content exceeds the set height.
<div style="background-color:green;border:1px solid red;width:81px;height:60px;overflow:scroll">
<div>hello world</div>
<div style="background-color:red;opacity:0.4;">
<table>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
</div>
</div>
Alternative Solutions:
Solution Using calc():
Instead of setting a fixed height for the .inner element, you can use the calc() function to dynamically calculate the height based on its parent container. This makes it easier to maintain as you only need to update one value instead of two if the component's height changes.
.outer {
background-color: green;
border: 1px solid red;
width: 81px;
height: 60px;
}
.inner {
background-color: red;
opacity: 0.4;
height: calc(100% - 1em);
overflow: scroll;
}
<div class="outer">
<div>hello world</div>
<div class="inner">
<table>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
</div>
</div>
Solution Using position: absolute:
Another approach is to utilize position: absolute for the .header within the .outer div which has been styled with padding-top and box-sizing: border-box for better layout control.
The .outer div should have position: relative so that the .header's position can be controlled absolutely. Adding padding-top with box-sizing helps establish the proper layout dimensions.
In this solution, the .inner element retains a height of 100% to cover the entire contents within the .outer div, while also having overflow: scroll enabled.
.outer {
position: relative;
box-sizing: border-box;
padding-top: 1em;
background-color: green;
border: 1px solid red;
width: 81px;
height: 60px;
}
.header {
position: absolute;
top: 0;
}
.inner {
height: 100%;
overflow: scroll;
background-color: red;
opacity: 0.4;
}
<div class="outer">
<div class="header">hello world</div>
<div class="inner">
<table>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
</div>
</div>