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

CSS布局异常求助:文本与按钮顺序颠倒且位置偏移

解决文本与按钮不居中、按钮位置异常的问题

问题根源

  • .hero-box设置了position: absolute,直接脱离了父元素.hero的flex布局流,导致.hero里的居中配置完全失效,内容自然跑到容器顶部。
  • .hero-description的margin: auto在脱离文档流的容器里无法发挥作用,反而可能打乱元素的默认排版逻辑。

修复方案

  1. 删除.hero-box的position: absolute,让它回到父元素的flex布局体系中;
  2. 给.hero加上justify-content: center,配合原本的align-items: center,实现子元素的垂直+水平双居中;
  3. 给.hero-description添加margin-bottom,让按钮和文本之间留出合理间距,确保按钮稳定显示在文本下方。

修改后的完整代码

CSS 代码

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Inter", sans-serif;
  color: #444;
  padding: 10px;
}

.hero {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; /* 新增:垂直居中 */
  padding: 0;
  margin: 0;
  height: 95vh;
  background-image: linear-gradient( to bottom, rgba(255, 255, 255, 0.9) 33%, hsla(224, 62%, 29%, 0.9), rgba(228, 24, 27, 0.8)), url(../Images/moscow.jpg);
  background-size: cover;
  clip-path: polygon(100% 0, 100% 85%, 50% 100%, 0 85%, 0 0);
}

.hero-box {
  text-align: center; /* 保留文本居中,移除position:absolute */
}

.hero-description {
  margin: 0 auto 20px; /* 修改:上下margin为0,底部留20px间距 */
  max-width: 66%;
  text-align: center;
  letter-spacing: 1.5px;
}

.hero-btn {
  display: inline-block;
  color: #444;
  background-color: #fff;
  padding: 10px;
  text-decoration: none;
  border: 1px solid #444;
  border-radius: 5px;
  text-transform: uppercase;
  font-family: inherit;
  font-weight: 600;
}

.hero-btn:hover {
  color: #555;
  background-color: #f1f1f1;
  padding: 11px;
  border: 1px solid #555;
}

HTML 代码(无需修改)

<div class="hero">
  <div class="hero-box">
    <h2 class="hero-description">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus facilis similique cupiditate temporibus excepturi, consectetur, expedita aut molestias fuga unde id nam doloremque laborum adipisci enim soluta ut nisi in!
    </h2>
    <a href="#" class="hero-btn">Visit</a>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:01:12