如何格式化CSS content属性内的文本内容
解决CSS content中文本格式化与换行问题
问题描述
需要对CSS伪元素content内的文本进行样式化:将"Agency Management"设置为加粗、8px字号,同时让剩余文本换行显示,但content不支持直接使用HTML,尝试用attr()拆分文本后无法实现换行效果。
解决方案
通过**换行符\A**配合white-space: pre-wrap实现文本换行,再用:first-line选择器单独设置首行(标题)的样式。具体步骤如下:
1. 更新HTML结构,添加数据属性
给开关标签添加存储标题和描述的data-*属性,方便在CSS中调用:
<div class="btn-container"> <label class="switch btn-color-mode-switch"> <input type="checkbox" name="color_mode" id="color_mode" value="1"> <label for="color_mode" data-agency-title="Agency Management" data-agency-desc="For agencies working on behalf of retail clients" data-business-title="Business Management." data-business-desc="For Single Merchants running 1+ stores" class="btn-color-mode-switch-inner" ></label> </label> </div>
2. 修改CSS样式,实现换行与文本格式化
在伪元素的content中用\A拼接标题和描述,开启white-space: pre-wrap解析换行符,再通过:first-line设置首行标题的样式:
/* 未选中状态:右侧显示Agency相关文本 */ .btn-color-mode-switch > label.btn-color-mode-switch-inner:before{ content: attr(data-agency-title) '\A' attr(data-agency-desc); position: absolute; font-size: 14px; font-weight: 500; top: 7px; right: 5px; white-space: pre-wrap; /* 解析换行符 */ text-align: right; width: 100px; /* 限制宽度,确保换行效果 */ } /* 设置首行标题样式 */ .btn-color-mode-switch > label.btn-color-mode-switch-inner:before:first-line{ font-weight: bold; font-size: 8px; } /* 未选中状态:左侧显示Business相关文本(滑块内) */ .btn-color-mode-switch > label.btn-color-mode-switch-inner:after{ content: attr(data-business-title) '\A' attr(data-business-desc); width: 150px; background: #464C42; color: white; border-radius: 15px; position: absolute; left: 2px; bottom: 2px; top: 2px; text-align: center; transition: all 0.3s ease; box-shadow: 0px 0px 6px -2px #111; padding: 5px 0px; white-space: pre-wrap; /* 解析换行符 */ display: flex; align-items: center; justify-content: center; } /* 设置滑块内首行标题样式 */ .btn-color-mode-switch > label.btn-color-mode-switch-inner:after:first-line{ font-weight: bold; font-size: 8px; } /* 选中状态:滑块切换到右侧,显示Agency相关文本 */ .btn-color-mode-switch input[type="checkbox"]:checked + label.btn-color-mode-switch-inner:after{ content: attr(data-agency-title) '\A' attr(data-agency-desc); left: 100px; background: #469DA3; } /* 选中状态:左侧显示Business相关文本 */ .btn-color-mode-switch input[type="checkbox"]:checked + label.btn-color-mode-switch-inner:before{ content: attr(data-business-title) '\A' attr(data-business-desc); right: auto; left: 20px; text-align: left; }
关键说明
\A是CSS中的换行转义字符,配合white-space: pre-wrap可以让浏览器解析并显示换行。:first-line选择器可以精准控制文本块的首行样式,满足标题加粗、缩小字号的需求。- 设置合适的宽度可以确保描述文本自动换行,避免内容溢出。
内容的提问来源于stack exchange,提问作者Vesta Nassone
相关产品推荐
相关产品推荐

