如何在div内居中垂直文本?可隐藏侧边栏标题居中技术问询
解决垂直旋转标题在侧边栏头部居中的问题
嘿,我懂你的困扰——旋转后的文本确实没法用普通的text-align:center来居中,这是因为transform:rotate只是视觉上旋转了元素,但元素在布局流里的占位还是原来的水平方向尺寸,常规居中方法自然就失效了。下面给你两个简单好用的解决方案:
方案一:Flexbox布局(最推荐)
直接把sidebar_header改成flex容器,利用flex的居中属性轻松搞定,代码修改如下:
修改后的完整CSS
#horizontal_panel { height: 300px; background-color: powderblue; } #sidebar { width: 20%; height: 100%; background-color: green; float: right; } #sidebar_header { background-color: red; width: 30%; height: 100%; float: left; /* 新增flex布局,实现垂直+水平双居中 */ display: flex; align-items: center; justify-content: center; } #sidebar_title { transform: rotate(-90deg); /* 防止标题换行,保证完整显示 */ white-space: nowrap; } #sidebar_contents { background-color: yellow; width: 70%; height: 100%; float: left; }
这个方法的优势是代码简洁,不需要额外计算位置,flex会自动帮你把旋转后的标题在容器里完美居中,完全适配你原来的隐藏/显示逻辑。
方案二:绝对定位+Transform(精确控制)
如果你需要更精细的位置调整,可以用绝对定位结合translate和rotate,修改后的CSS如下:
#horizontal_panel { height: 300px; background-color: powderblue; } #sidebar { width: 20%; height: 100%; background-color: green; float: right; } #sidebar_header { background-color: red; width: 30%; height: 100%; float: left; /* 设置为定位容器,让子元素可以基于它绝对定位 */ position: relative; } #sidebar_title { position: absolute; /* 先把元素左上角移到容器中心 */ top: 50%; left: 50%; /* 先平移自身的一半距离实现居中,再执行旋转 */ transform: translate(-50%, -50%) rotate(-90deg); white-space: nowrap; } #sidebar_contents { background-color: yellow; width: 70%; height: 100%; float: left; }
这个方法的逻辑是:先通过top:50%和left:50%把元素的左上角放到容器中心,再用translate(-50%, -50%)把元素的中心和容器中心对齐,最后旋转,这样就能保证旋转后的标题完全居中。
两种方案都不会影响你原来的JS隐藏/显示功能,sidebar_header.offsetWidth会正确计算容器宽度,旋转后的标题不会干扰布局尺寸。你直接替换掉原来的CSS代码,就能看到垂直标题完美居中的效果啦!
内容的提问来源于stack exchange,提问作者barciewicz
相关产品推荐
相关产品推荐

