使用W3.CSS实现手风琴时按钮内文本无法自动换行问题
问题解决方法
问题原因
W3.CSS框架的.w3-button类默认配置了white-space: nowrap属性,强制按钮内所有文本不自动换行,是导致溢出问题的核心原因。同时当前代码存在HTML规范问题:<button>标签内嵌套了块级元素<div>,不符合HTML语法要求,也可能引发布局异常。
修复方案
- 第一步:调整HTML结构,把按钮内的
<div class="job_briefly">替换为行内元素<span class="job_briefly">,符合语法规范。 - 第二步:添加自定义CSS规则,覆盖W3.CSS的默认按钮不换行配置:
.w3-button.job_title { /* 允许文本自动换行 */ white-space: normal; /* 长单词/连续字符强制断行 */ word-wrap: break-word; /* 按钮撑满父容器宽度,避免超出视口 */ width: 100%; }
修正后的完整代码示例
<!-- 把自定义CSS加到页面head的style标签内 --> <style> .w3-button.job_title { white-space: normal; word-wrap: break-word; width: 100%; } </style> <button onclick="myFunction('uid22222')" class="w3-button w3-left-align job_title"> JOB TITLE HERE - WHICH MIGHT BE VERY AND VERY AND VERY AND VERY LONGGGGGG SO NEEDS TO WRAP WHEN VIEWED IN A NARROW VIEWPORT LIKE A PHONE SCREEN <span class="job_briefly"> <br>Job Description: Some text here which briefly describes the vacancy and which needs to wrap when viewed in a narrow viewport, which happens ok when viewing the "hide" text below.. <br>And some more text. </span> </button> <div id="uid22222" class="w3-hide job_hidden"> Location details. <br><b>Organisation Name</b> <br>Pay & Hours &/or Benefits. <br>Apply on or before xxx date. </div> <script> function myFunction(id) { var x = document.getElementById(id); if (x.className.indexOf("w3-show") == -1) { x.className += " w3-show"; } else { x.className = x.className.replace(" w3-show", ""); } } </script>
内容的提问来源于stack exchange,提问作者Philip Caplan
相关产品推荐
相关产品推荐

