求助:如何实现类似Book Depository的容器内容水平滚动效果?
Hey there! I’ve tackled this exact horizontal scroll issue with Bootstrap layouts before, so let’s get your book list scrolling smoothly just like Book Depository. Here’s a reliable solution tailored to your existing code structure:
Core CSS Adjustments
The main culprits when this fails are usually Bootstrap’s default flex wrapping or elements getting squeezed. Add these styles to your CSS:
/* Target your main container */ .mainContent { overflow-x: auto; /* Enables horizontal scroll when content overflows */ overflow-y: hidden; /* Hides vertical scroll unless you need it */ padding-bottom: 1rem; /* Optional: Prevents scrollbar from covering bottom content */ } /* Adjust the row inside your container to prevent wrapping */ .mainContent .row { flex-wrap: nowrap; /* Forces all columns to stay in a single horizontal line */ margin-left: 0; /* Optional: Removes Bootstrap's default left margin to avoid extra scroll space */ margin-right: 0; /* Optional: Same for right margin */ } /* Style your book columns to maintain their width */ .mainContent .col-md-3 { /* Replace with your actual column class, e.g., col-md-4 */ flex-shrink: 0; /* Stops columns from being compressed to fit the container */ width: 250px; /* Set a fixed width for your book cards (adjust as needed) */ margin-right: 1.5rem; /* Optional: Adds spacing between book cards */ }
Why Your Previous Attempt Might Have Failed
Most likely, Bootstrap’s default .row has flex-wrap: wrap enabled, which forces columns to wrap to a new line instead of overflowing horizontally. Additionally, without flex-shrink: 0, your book columns would get squeezed to fit the container, so there’s no overflow to trigger scrolling.
Quick Testing Tip
Make sure the total width of all your book columns adds up to more than the width of .mainContent—this is what triggers the horizontal scroll. For example, if your container is 1000px wide and each card is 250px, 5 cards will create a 1250px wide row, which will scroll perfectly.
If you’re using an older version of Bootstrap with float-based layouts instead of flex, use this alternative:
.mainContent { overflow-x: auto; overflow-y: hidden; white-space: nowrap; /* Keeps inline elements in one line */ } .mainContent .col-md-3 { display: inline-block; /* Makes columns line up horizontally */ white-space: normal; /* Resets white-space for content inside the card */ width: 250px; margin-right: 1.5rem; }
内容的提问来源于stack exchange,提问作者user6106197

