text-transform与hyphens无法同时生效的问题求解(Chrome macOS环境)
解决Chrome中text-transform: uppercase导致hyphens失效的问题
问题背景
在Chrome 121.0+版本、macOS 14.2系统环境下,当为文本元素添加text-transform: uppercase属性将文本转为全大写时,hyphens: auto自动断字功能会失效,长文本无法按预期自动换行断字。
解决方案
方案一:伪元素模拟大写效果(推荐)
通过伪元素实现全大写展示,保留原文本的断字逻辑,具体代码如下:
CSS代码
p { width: 50px; border: 1px dashed #555; /* 隐藏原文本,但保留其断字计算逻辑 */ color: transparent; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; position: relative; } .uppercase::after { /* 读取data-text属性内容并转为大写 */ content: attr(data-text); text-transform: uppercase; color: #000; position: absolute; top: 0; left: 0; right: 0; }
HTML代码
<p lang="en">A conversation about sustainable carsharing.</p> <p lang="en" class="uppercase" data-text="A conversation about sustainable carsharing."></p>
原理:原文本保持布局占位并参与断字计算,伪元素读取预设文本并转为大写后覆盖在原位置,兼顾大写效果和自动断字功能。
方案二:手动插入软连字符
如果文本内容固定,可在需要断字的位置手动插入软连字符­,配合原有属性使用:
HTML代码
<p lang="en" class="uppercase">A con­ver­sa­tion about sus­tain­able car­shar­ing.</p>
CSS代码(保留原有配置)
p { width: 50px; border: 1px dashed #555; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } .uppercase { text-transform: uppercase; }
内容的提问来源于stack exchange,提问作者ReneP
相关产品推荐
相关产品推荐

