You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在flex布局中实现可变宽高比图表旋转Y轴标签的正确对齐

方案1:调整结构实现最稳定的适配(推荐)

修改后HTML

把Y轴标签、图表、X轴标签封装到独立的横向容器内,隔离标题和图表区域的布局逻辑:

<div class="grid">
     <div class="chart">
          <h2>Test 1</h2>      
          <div class="graph-container">
            <div class="graphAxisY">test y lable</div>
            <div class="graph-wrapper">
              <Graph class="graph">(This is the graph)</Graph>
              <div class="graphAxisX">test x lable</div>
            </div>
          </div>
     </div>
     <div class="chart">
          <h2>Test 2</h2>      
          <div class="graph-container">
            <div class="graphAxisY">test y lable</div>
            <div class="graph-wrapper">
              <Graph class="graph">(This is the graph)</Graph>
              <div class="graphAxisX">test x lable</div>
            </div>
          </div>
     </div>
</div>

修改后CSS

.grid{
  display: grid;
  grid-template-columns: repeat(auto-fit,33%);
  gap: 0.8vw;
}
.chart{
  display: flex;
  flex-direction: column;
}
/* 横向容器,Y轴在左、图表区在右 */
.graph-container {
  display: flex;
  align-items: center;
  flex: 1;
}
.graphAxisY{
  /* 替代原有transform方案,无需固定偏移 */
  writing-mode: vertical-lr;
  transform: rotate(180deg);
  background-color: transparent; 
  z-index: 100;
  margin-right: 8px;
}
/* 图表区纵向排列,图表在上X轴在下 */
.graph-wrapper {
  display: flex;
  flex-direction: column;
  flex: 1;
}
.graphAxisX {
  text-align: center;
  margin-top: 4px;
}

适配逻辑

  • 新增的.graph-container采用横向flex布局,align-items: center属性会自动让Y轴标签在图表的纵向中心位置,完全不受图表宽高比影响
  • 用writing-mode实现纵向文字,替代原来的固定百分比偏移,不需要计算旋转后的位移值,布局不会随容器尺寸变化错位

方案2:不修改现有HTML的快速适配

如果不想调整HTML结构,可通过绝对定位实现自适应居中:

.chart{
  display: flex;
  flex-direction: column;
  padding-right: 0.8vw;
  padding-left: 20px; /* 预留Y轴标签展示空间,可自行调整数值 */
  position: relative;
}
.graphAxisY{
  position: absolute;
  left: 0;
  top: 50%;
  transform-origin: left center;
  transform: rotate(270deg) translateY(-50%);
  background-color: transparent; 
  z-index: 100; 
}

内容的提问来源于stack exchange,提问作者Akila Uyanwatta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:36:04