CSS Transform旋转文字不换行溢出DIV,如何实现旋转同时保持文字在容器内换行?
问题解决办法
CSS transform属于视觉渲染层面的变换,不会修改元素的原始盒模型参数和文档流占位。你给水平排布的文本加90度旋转后,文本原始的水平长度会变成垂直方向的展示高度,直接超出父容器的高度范围,同时行内元素<span>默认宽度跟随内容长度,不会触发自动换行,最终就出现了文本溢出的问题。
方案1:保留transform旋转的修改方案
你需要给旋转的文本元素补充以下配置:
- 将
<span>设置为inline-block类型,支持手动设置宽度和文本换行规则 - 给
<span>设置和父容器高度匹配的宽度,旋转后这个宽度就对应了垂直方向的可展示长度 - 添加自动换行规则,保证长文本超出宽度后自动折行
- 可选调整旋转原点,修正位置偏移
修改后的完整代码如下:
<div style="display: flex; background-color: lightblue; align-items: center; margin: 6in 1in 1in; height: 200px; padding: 0 15px;"> <span style=" display: inline-block; width: 170px; /* 可根据父容器实际高度调整数值 */ transform: rotate(90deg); transform-origin: center center; font-size: 12pt; text-align: center; overflow-wrap: break-word; ">Blessings to you my Sister as you celebrate this milestone. Love and light, Eva </span> </div>
方案2:使用writing-mode实现竖排(更推荐)
如果不需要严格依赖transform实现旋转,可以直接用CSS的writing-mode属性实现竖排文本,元素的盒模型会自动适配竖排尺寸,不会出现占位和视觉尺寸不一致的问题,自动适配容器换行:
<div style="display: flex; background-color: lightblue; align-items: center; justify-content: center; margin: 6in 1in 1in; height: 200px;"> <span style=" writing-mode: vertical-rl; rotate: 180deg; /* 调整文字方向为从上到下、从左到右的阅读顺序 */ font-size: 12pt; text-align: center; padding: 0 15px; ">Blessings to you my Sister as you celebrate this milestone. Love and light, Eva </span> </div>
内容的提问来源于stack exchange,提问作者Ian Vink
相关产品推荐
相关产品推荐

