I’m working on a web layout where I need the .cart-items-container
to occupy the remaining space above the .cart-rest-details
section. The .cart-items-container
should be scrollable if its content overflows, and the .cart-rest-details
should remain fixed at the bottom of the viewport. But I’m encountering issues with the layout on mobile devices.
Here I’ve attached my codebase.
.cart-container {
display: flex;
flex-direction: column;
gap: 16px;
width: 100%;
height: 100vh;
}
.cart-items-container {
display: flex;
flex-direction: column;
}
.cart-items {
padding: 8px;
max-height: 300px;
overflow: auto;
background-color: #EEEEEE;
border: 2px solid orange
}
.cart-rest-details {
display: flex;
flex-direction: column;
gap: 4px;
width: 90%;
padding: 5%;
background-color: dodgerblue;
color: white;
}
@media screen and (max-width: 768px) {
.cart-items-container {
flex-grow: 1;
}
.cart-items {
flex-grow: 1;
max-height: none;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="cart-container">
<div class="cart-items-container">
<h1>Cart Items</h1>
<div class="cart-items">
<p>Item 1</p>
<p>Item 2</p>
<p>Item 3</p>
<p>Item 4</p>
<p>Item 5</p>
<p>Item 6</p>
<p>Item 7</p>
<p>Item 8</p>
<p>Item 9</p>
<p>Item 10</p>
<p>Item 11</p>
<p>Item 12</p>
<p>Item 13</p>
<p>Item 14</p>
<p>Item 15</p>
<p>Item 16</p>
<p>Item 17</p>
<p>Item 18</p>
<p>Item 19</p>
<p>Item 20</p>
<p>Item 21</p>
<p>Item 22</p>
<p>Item 23</p>
<p>Item 24</p>
<p>Item 25</p>
</div>
</div>
<div class="cart-rest-details">
<p>Description 1</p>
<p>Description 2</p>
<p>Description 3</p>
<p>Description 4</p>
<p>Description 5</p>
</div>
</div>
</body>
</html>
On mobile devices, the .cart-items-container
does not properly fill the remaining space above .cart-rest-details
, and the .cart-items
section does not scroll as expected.
Current behavior:
Expected behavior:
2
Answers
Try adding
min-height: 0;
to.cart-items-container
.Because by default, a child of flexbox will not shrink below
min-content
(which is determined by its child content) even withflex-shrink
set to a non-zero value. By settingmin-height: 0
overrides this behavior that allows it to shrink properly, thus the scroll bar will appear as expected.I’ve added
resize: both
on your .cart-container so you can drag from bottom right to see how this adapts:The flexbox algorithm treats your max-height as a preferred height and won’t shrink below it, so setting a super low height and allowing flex grow to do the magic for us should yield the desired result