如何实现MaterializeCSS选择框选中选项文本换行
解决MaterializeCSS收起状态选择框文本换行问题
问题背景
基于MaterializeCSS的表单中,选择框收起状态下的长文本被单行截断,仅展开的下拉选项能正常换行,需要让收起状态的文本完整显示(表单由django-material生成,核心问题在MaterializeCSS的选择组件)。
示例元素结构:
<div class="select-field col s12 required" id="id_formset-organisation_answers-1-question_container"> <label for="id_formset-organisation_answers-1-question">Question</label> <div class="select-wrapper"> <input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-f739ead4-0165-a758-650e-74ba61fac041"> <ul id="select-options-f739ead4-0165-a758-650e-74ba61fac041" class="dropdown-content select-dropdown" tabindex="0"> <li id="select-options-f739ead4-0165-a758-650e-74ba61fac0410" tabindex="0"> <span>---------</span> </li> <li id="select-options-f739ead4-0165-a758-650e-74ba61fac0411" tabindex="0"> <span>VERY LONG TEXT 1</span> </li> <li id="select-options-f739ead4-0165-a758-650e-74ba61fac0412" tabindex="0" class="selected"> <span>VERY LONG TEXT 2</span> </li> <li id="select-options-f739ead4-0165-a758-650e-74ba61fac0413" tabindex="0"> <span>VERY LONG TEXT 3</span> </li> </ul> <svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"> <path d="M7 10l5 5 5-5z"></path> <path d="M0 0h24v24H0z" fill="none"></path> </svg> <select id="id_formset-organisation_answers-1-question" name="formset-organisation_answers-1-question" tabindex="-1"> <option value="">---------</option> <option value="1">VERY LONG TEXT 1</option> <option value="2" selected="selected">VERY LONG TEXT 2</option> <option value="3">VERY LONG TEXT 3</option> </select> </div> <div class="help-block">The question.</div> </div>
之前尝试的无效方案
CSS尝试
仅能修改颜色和高度,但无法实现换行:
input.select-dropdown { /* 生效的样式 */ color:green; min-height: 20rem; /* 无效的样式 */ display: inline-block; min-height: -moz-fit-content; min-height: fit-content; overflow-wrap: break-word; z-index:10; }
JS尝试
仅能修改文本颜色,无法控制文本换行:
/** * Resize select dropdowns to fit text */ window.addEventListener('load', function() { document.querySelectorAll('select').forEach((el) => { console.log("Styling element " + el.id); el.M_FormSelect.input.style.cssText="color:red;"; console.log(el.M_FormSelect.input.style); }); });
有效解决方案
核心CSS修复
MaterializeCSS默认给input.select-dropdown设置了white-space: nowrap和overflow: hidden,这是文本单行截断的根源,通过以下CSS覆盖即可:
/* 允许选择框文本换行,取消单行限制 */ input.select-dropdown { white-space: normal !important; overflow: visible !important; min-height: auto; height: auto; padding-top: 1rem; padding-bottom: 1rem; } /* 让选择框容器高度自适应内容 */ .select-wrapper { height: auto !important; } /* 修正下拉箭头的垂直居中位置 */ .select-wrapper .caret { position: absolute; right: 1rem; top: 50%; transform: translateY(-50%); }
原理说明
white-space: normal取消强制单行限制,允许文本自动换行overflow: visible确保换行后的文本不会被容器裁剪- 调整容器和输入框高度为自动,避免固定高度导致内容溢出或空白
- 修正下拉箭头位置,防止因容器高度变化导致箭头错位
内容的提问来源于stack exchange,提问作者florianm
相关产品推荐
相关产品推荐

