如何修改Select2选择框(含箭头与选中项)的高度?
修改Select2选择框高度的解决方案
问题描述
尝试修改带箭头和选中项的Select2选择框高度,已尝试为.select2-container、.selection、.select2-selection、.select2-selection--single及#select2-searchSelect-container设置height属性,但均未生效。相关代码如下:
HTML代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="styles.css"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <title>Hello, world!</title> </head> <body> <h1>Hello, world!</h1> <select class="form-select" id="searchSelect"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> </select> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" crossorigin="anonymous"></script> <script src="script.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> </body> </html>
CSS代码
body{ padding: 25px; } #select2-searchSelect-container { height: 50px; /* This didn't work */ }
JavaScript代码
$( document ).ready(function() { $("#searchSelect").select2(); });
解决方案
Select2单选择器的高度调整需要同时覆盖外层容器、内容容器和下拉箭头的样式,还要考虑Bootstrap的样式优先级,替换原有CSS为以下代码即可生效:
body{ padding: 25px; } /* 调整Select2核心选择框容器高度,确保垂直居中 */ .select2-container--default .select2-selection--single { height: 50px !important; display: flex; align-items: center; } /* 调整选中内容的行高与内边距,避免内容错位 */ #select2-searchSelect-container { line-height: 50px; padding: 0 12px; } /* 调整下拉箭头的高度与位置,匹配容器高度 */ .select2-container--default .select2-selection--single .select2-selection__arrow { height: 48px; right: 8px; }
关键说明
- 使用
!important是为了强制覆盖Select2和Bootstrap的默认样式优先级; - 通过
flex布局确保选中内容垂直居中,避免手动调整内边距的繁琐; - 同步调整箭头高度,保证视觉上的统一对齐。
内容的提问来源于stack exchange,提问作者minhson Bui
相关产品推荐
相关产品推荐

