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

如何使第一个元素居中,第二个元素紧邻其右侧同行显示?

实现第一个元素居中,第二个元素紧贴其右侧显示

当前代码中两个元素整体居中,需求是让红框(第一个元素)在页面水平居中,绿框(第二个元素)紧贴红框右侧同行显示。以下是可行的解决方案:

方法一:嵌套容器实现(推荐,无需硬编码宽度)

通过嵌套容器,让内部容器跟随红框居中,绿框绝对定位紧贴红框右侧:

/* 父容器:负责将内部容器整体水平垂直居中 */
.container {
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh; /* 可选,让容器占满视口高度,便于查看垂直居中效果 */
}

/* 内部容器:作为绿框定位的基准 */
.inner-wrap {
  position: relative;
}

.red {
  width: 200px;
  height: 100px;
}

.green {
  position: absolute;
  left: 100%; /* 紧贴红框右侧 */
  top: 0;
  width: 200px;
  height: 100px;
}

对应的HTML:

<div class="container">
  <div class="inner-wrap">
    <svg class="red" width="200" height="100" viewBox="0 0 200 100" fill="none" >
      <rect width="200" height="100" fill="#FF0000"/>
    </svg>
    <svg class="green" width="200" height="100" viewBox="0 0 200 100" fill="none" >
      <rect width="200" height="100" fill="#008000"/>
    </svg>
  </div>
</div>

方法二:绝对定位精准偏移

通过计算页面中心与红框宽度的偏移量,直接定位绿框位置:

.container {
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  min-height: 100vh;
}

.red {
  width: 200px;
  height: 100px;
}

.green {
  position: absolute;
  /* 50%是页面水平中心,加上红框宽度的一半(100px),刚好对齐红框右边缘 */
  left: calc(50% + 100px);
  top: 50%;
  transform: translateY(-50%); /* 垂直方向对齐红框 */
  width: 200px;
  height: 100px;
}

对应的HTML:

<div class="container">
  <svg class="red" width="200" height="100" viewBox="0 0 200 100" fill="none" >
    <rect width="200" height="100" fill="#FF0000"/>
  </svg>
  <svg class="green" width="200" height="100" viewBox="0 0 200 100" fill="none" >
    <rect width="200" height="100" fill="#008000"/>
  </svg>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:03:28