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

如何实现Header文字页面居中且右侧同高按钮对齐?

解决Header文字居中与右侧按钮对齐问题

当前Header中的“Please Center Me”文本因右侧搜索图标导致无法真正居中,以下是调整后的代码,可实现文字完全居中、按钮固定在右侧且与文字同高度的效果:

修改后的HTML代码

<header>
    <h1>Please Center Me</h1>
    <span class="material-icons header-icon">search</span>
</header>

修改后的CSS代码

header {
    width: 100%;
    background-color: #1DA87F;
    color: #EBEF8E;
    font-size: 1.5em;
    display: flex;
    align-items: center;
    padding: 0.5rem 0;
}

header h1 {
    flex: 1;
    text-align: center;
    margin: 0;
}

.header-icon {
    font-size: 1.5em;
    margin-right: 1rem;
}

关键调整说明

  • 给header添加align-items: center,确保内部元素垂直方向居中对齐
  • 给h1设置flex: 1,让它占据Header内除按钮外的所有空间,再通过text-align: center实现文本在整个Header范围内的水平居中,彻底避免按钮对居中位置的干扰
  • 移除原代码中margin: auto这类会干扰flex空间分配的属性,同时给按钮添加右侧间距优化视觉体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:05:13