如何在Bootstrap中使下拉菜单宽度与文本框宽度一致
实现Bootstrap下拉菜单宽度与文本框一致
需求:下拉菜单的尺寸需自动匹配文本框宽度,而非相对于页面宽度。
解决方案
通过调整Bootstrap默认样式,结合内置类实现宽度自适应:
- 给下拉菜单添加
w-100类,让它继承父容器宽度 - 移除下拉菜单默认的最小宽度限制,确保完全匹配文本框宽度
修改后的完整代码
<!doctype html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <style> .dropdown-menu { min-width: unset; /* 移除默认最小宽度限制 */ } </style> </head> <body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <div class="dropdown position-relative"> <input type="text" class="form-control dropdown-toggle" data-bs-toggle="dropdown" value="All Sheets" aria-expanded="false" data-bs-auto-close="outside" readonly> <div class="dropdown-menu p-0 w-100"> <div class="list-group"> <label class="list-group-item"> <input class="form-check-input me-1" type="checkbox" value=""> Sheet1 </label> <label class="list-group-item"> <input class="form-check-input me-1" type="checkbox" value=""> Sheet2 </label> <label class="list-group-item"> <input class="form-check-input me-1" type="checkbox" value=""> Sheet3 </label> <label class="list-group-item"> <input class="form-check-input me-1" type="checkbox" value=""> Sheet4 </label> </div> </div> </div> </body> </html>
说明
position-relative给父容器.dropdown添加,确保下拉菜单相对于文本框定位w-100让.dropdown-menu宽度占满父容器,与文本框宽度完全对齐min-width: unset消除Bootstrap默认的下拉菜单最小宽度限制,适配文本框的任意宽度
内容的提问来源于stack exchange,提问作者Code Guy
相关产品推荐
相关产品推荐

