- I have a layout where two divs (left and right) are side by side using Flexbox. I want the following behavior:
- The right div should determine the height of the container based on its content.
- The left div should expand to match the height of the right div.
- If the left div has more content than the right div, it should scroll, but the right div should never have a scrollbar, since if there is more content in right div the whole container grows in height.
Here is the code Iām using:
.main-container {
display: flex;
width: 60%;
border: 2px solid #333;
align-items: stretch; /* Ensures both divs stretch to the same height */
}
.left-div, .right-div {
flex: 1;
padding: 20px;
border: 1px solid #ccc;
}
.left-div {
background-color: #e3f2fd;
overflow-y: auto; /* Should scroll if content exceeds right div's height */
}
.right-div {
background-color: #ffeb3b;
overflow: hidden; /* No scroll on the right div */
}
ul {
list-style-type: none;
padding: 0;
}
<div class="main-container">
<div class="left-div">
<h3>Left Div (scrolls if content exceeds)</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
<li>Item 15</li>
</div>
<div class="right-div">
<h3>Right Div</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</div>
</div>
What I expect
What I am trying to get as output
Thank you š
2
Answers
I tried to solve it with JavaScript. So, the idea is to check the
scrollHeight
of right div and set themax-height
of left div depending on that.Also, added two buttons to check if it works as expected.
Here’s another solution, using a little bit of JS, too.