如何用HTML/CSS实现header标题相对视口居中而非在两侧div间居中?
导航栏标题相对视口居中实现问题
我目前正在为开发中的站点设计头部导航栏,期望实现左侧展示logo、中间展示标题、右侧展示用户账户信息的布局。
下图是我预期的设计效果图,其中虚线框代表div:
我已经基于HTML/CSS完成了部分开发,但无法实现标题相对于浏览器视口居中的效果,当前实现效果如下:
可以看到当前标题是在左侧logo和右侧账户信息两个div之间居中,而非相对于整个视口居中,导致页面视觉效果不协调,因此需要实现标题相对视口居中的效果。我的代码如下:
.headerBarArea { background-color: #7785A2; border: 0; padding: 0; width: 100%; display: inline-block; text-align: center; } .logoArea { display: inline; text-align: center; float: left; border: lawngreen; border-style: dashed; border-width: 1px; } .minesLogo { width: 96px; } .titleArea { display: inline-block; text-align: center; border: lawngreen; border-style: dashed; border-width: 1px; } .siteTitle { color: white; } .pageTitle { color: white; } .userAccountArea { display: inline; text-align: center; float: right; border: lawngreen; border-style: dashed; border-width: 1px; } .userAccountIcon { float: left; width: 35px; } .userAccountText { float: right; }
<div className="headerBarArea"> <div className="logoArea"> <img src="assets/mines_logo_stacked.png" className="minesLogo" /> </div> <div className="titleArea"> <h2 className="siteTitle">This is my site Title</h2> <h3 className="pageTitle">Page Title</h3> </div> <div className="userAccountArea"> <img src="assets/user_account.png" className="userAccountIcon" /> <span className="UserAccountText">John Smith (Student)</span> </div> </div>
请问有什么方案可以让标题div相对于视口居中,而非在两侧的div之间居中?
解决方案
这里提供两种可直接落地的实现方案,均能满足需求:
方案1:Grid布局(优先推荐)
该方案基于现代CSS布局能力,不需要脱离文档流,天然适配响应式,不会出现元素重叠问题:
仅需修改.headerBarArea和.titleArea的CSS规则即可:
.headerBarArea { background-color: #7785A2; border: 0; padding: 0; width: 100%; display: grid; grid-template-columns: auto 1fr auto; /* 定义三列布局:左右列宽适配内容,中间列占剩余全部宽度 */ align-items: center; /* 可选,实现所有子元素垂直居中对齐 */ } .titleArea { justify-self: center; /* 让中间列的内容在列内水平居中,最终呈现相对整个视口居中的效果 */ text-align: center; border: lawngreen dashed 1px; }
左右两侧的logoArea和userAccountArea不需要额外修改,Grid会自动将其放置在左右两列。如果标题宽度超过中间列宽度会自动换行,不会遮挡左右两侧内容。
方案2:绝对定位法
实现逻辑简单,适合需要兼容老旧浏览器的场景:
给父容器加相对定位作为定位参照物,中间标题用绝对定位脱离文档流,基于父容器居中:
.headerBarArea { background-color: #7785A2; border: 0; padding: 0; width: 100%; position: relative; /* 新增,作为子元素绝对定位的参照物 */ min-height: 80px; /* 按实际内容高度调整,防止浮动元素导致父容器高度塌陷 */ } .logoArea { position: relative; z-index: 10; /* 提升层级,防止被中间标题遮挡 */ /* 原有其他规则保持不变 */ } .titleArea { position: absolute; left: 0; right: 0; margin: 0 auto; width: fit-content; text-align: center; border: lawngreen dashed 1px; } .userAccountArea { position: relative; z-index: 10; /* 提升层级,防止被中间标题遮挡 */ /* 原有其他规则保持不变 */ }
注意该方案如果遇到小屏且标题过长的场景,可能会和左右元素重叠,可通过给.titleArea加左右padding(值大于左右元素的最大宽度)或者配合媒体查询调整解决。
内容的提问来源于stack exchange,提问作者Jyclop
相关产品推荐
相关产品推荐

