Bootstrap网页小屏幕布局换行:如何启用横向滚动固定布局?
解决Bootstrap栅格取消响应式、启用横向滚动的问题
你的问题核心是Bootstrap的响应式栅格默认在小屏幕下会让列宽度变成100%并换行,要实现保持布局不变、横向滚动的效果,需要做以下修改:
关键修改点
- 覆盖Bootstrap列的响应式行为:
col-lg-*仅在大屏幕生效,小屏幕下会自动堆叠,所以要给列设置固定的flex基础宽度,让它们始终保持比例不换行 - 确保滚动容器和行的样式优先级高于Bootstrap的默认样式
- 修正HTML里的重复
</head>标签(你的代码里写了两次,会导致样式加载异常)
修改后的CSS代码
/* 滚动容器:启用横向滚动,禁止内容换行 */ .scrolling-wrapper { overflow-x: auto; white-space: nowrap; /* 给容器加最小宽度,确保内容不会被压缩 */ min-width: 100%; } /* 覆盖Bootstrap row的默认flex-wrap,强制不换行 */ .scrolling-wrapper .row { display: flex; flex-wrap: nowrap; /* 让行的宽度随内容自适应,不被容器限制 */ width: auto; } /* 给列设置固定的flex比例,替代Bootstrap的响应式列类 */ .scrolling-wrapper .col-lg-6 { flex: 0 0 50%; /* 对应原col-lg-6的宽度比例 */ max-width: 50%; } .scrolling-wrapper .col-lg-4 { flex: 0 0 33.3333%; /* 对应原col-lg-4的宽度比例 */ max-width: 33.3333%; } .scrolling-wrapper .col-lg-2 { flex: 0 0 16.6667%; /* 对应原col-lg-2的宽度比例 */ max-width: 16.6667%; } /* 卡片高度设置 */ .small-game .card { height: 100px; } .medium-game .card { height: 200px; } .large-game .card { height: 300px; } .card-img-top { width: 100%; height: 100%; object-fit: cover; }
修改后的HTML代码
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dalton's Game Portfolio</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <!-- Custom CSS --> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container mt-5"> <h1 class="text-center">Dalton's Game Portfolio</h1> <div class="scrolling-wrapper"> <div class="row g-0"> <!-- Large games --> <div class="col-lg-6"> <div class="card large-game"> <img src="path-to-large-game-image.png" class="card-img-top" alt="Large Game"> </div> </div> <!-- Medium Game --> <div class="col-lg-4"> <div class="card medium-game"> <img src="path-to-medium-game-image.png" class="card-img-top" alt="Medium Game"> </div> </div> <!-- Small Game --> <div class="col-lg-2"> <div class="card small-game"> <img src="path-to-small-game-image.png" class="card-img-top" alt="Small Game"> </div> </div> </div> </div> </div> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </body> </html>
额外说明
- 给
.scrolling-wrapper加min-width:100%是为了确保容器在小屏幕下不会被压缩,内容超出时才会显示横向滚动条 - 用
scrolling-wrapper .row这样的嵌套选择器,是为了让自定义样式的优先级高于Bootstrap的默认样式,避免被覆盖 - 移除了冗余的jQuery和旧版Popper.js,Bootstrap 5已经不需要它们,用
bootstrap.bundle.min.js就包含了Popper
内容的提问来源于stack exchange,提问作者TryingMyBest
相关产品推荐
相关产品推荐

