如何实现Flexbox布局下元素可滚动而非内容重叠?
Fixing the 100% Height Item with Scrollable Content in Flexbox
Hey there! The issue you're facing is that your red .item has height: 100%, but when the internal text is too long, it pushes beyond the element's bounds and causes overlap. The fix is simple—we just need to add overflow handling to that specific item.
Updated CSS Code
html, body { width: 100%; height: 100%; margin: 0; /* Remove default browser margins to avoid unwanted page scrollbars */ padding: 0; } .container { display: flex; flex-wrap: wrap; justify-content: space-between; width: 100%; height: 100%; } .item { width: 100%; height: 100px; background: green; } .item:nth-child(2n) { height: 100%; background: red; overflow-y: auto; /* This line makes internal text scrollable when it exceeds the item's height */ }
Why This Works
overflow-y: autotells the browser to show a vertical scrollbar only when the content inside the item is taller than the item itself. This keeps the red item locked at 100% height of its flex container, while letting users scroll through the long text without breaking the layout.- The
margin: 0andpadding: 0onhtml, bodyeliminate default browser spacing that could cause the whole page to scroll unnecessarily.
Full Working HTML
Just drop the updated CSS into your <head> section, and your existing HTML structure will work perfectly:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>CSS Positioning Examples</title> <style> html, body { width: 100%; height: 100%; margin: 0; padding: 0; } .container { display: flex; flex-wrap: wrap; justify-content: space-between; width: 100%; height: 100%; } .item { width: 100%; height: 100px; background: green; } .item:nth-child(2n) { height: 100%; background: red; overflow-y: auto; } </style> </head> <body> <div class="container"> <div class="item">test</div> <div class="item"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> <!-- All your other Lorem Ipsum paragraphs go here --> </div> </div> </body> </html>
Now your red box will stay at 100% height of the container, and the long text inside will be scrollable without overlapping other elements.
内容的提问来源于stack exchange,提问作者softshipper




