如何垂直平移元素使其置于header与main content两个元素之间?
问题描述
现有基础垂直布局如下:
#header { background: yellow; height: 50px; } #bar { background: green; height: 50px; } #main-content { background: blue; height: 50px; }
<div id="header">header</div> <div id="bar">bar</div> <div id="main-content">main content</div>
需要调整为bar横向宽度缩小,且垂直方向位于header与main-content的衔接中间位置(即bar覆盖在两者的交界处,main-content上移,不再为bar单独预留整行高度)。尝试了容器嵌套方案但未达到预期:
#header { background: yellow; height: 50px; } #bar-container { position: relative; background: green; height: 50px; margin: 0 50px; } #bar { position: absolute; top: 50%; transform: translateY(-50%); } #main-content { background: blue; height: 50px; }
<div id="header">header</div> <div id="bar-container"> <div id="bar">bar</div> </div> <div id="main-content">main-content</div>
请问如何实现目标布局?
解决方案
这里提供两种简洁的实现方式:
方案1:绝对定位+负偏移
利用绝对定位让bar脱离文档流,同时调整位置使其居中于header和main-content之间:
#header { background: yellow; height: 50px; /* 作为bar的定位参考 */ position: relative; } #bar { background: green; height: 50px; /* 缩小横向宽度 */ margin: 0 50px; position: absolute; /* 向上偏移自身一半高度,刚好卡在header底部和main-content顶部中间 */ bottom: -25px; left: 0; right: 0; /* 文字垂直水平居中 */ display: flex; align-items: center; justify-content: center; } #main-content { background: blue; height: 50px; /* 给bar留出空间,避免被遮挡 */ margin-top: 25px; }
<div id="header">header</div> <div id="bar">bar</div> <div id="main-content">main content</div>
方案2:Grid布局(更简洁)
借助Grid的跨行列特性,直接控制元素位置:
.layout-container { display: grid; /* 定义两行,每行高度对应header和main-content的高度 */ grid-template-rows: 50px 50px; } #header { background: yellow; grid-row: 1 / 2; } #bar { background: green; height: 50px; margin: 0 50px; /* 让bar跨两行,垂直居中 */ grid-row: 1 / 3; align-self: center; display: flex; align-items: center; justify-content: center; } #main-content { background: blue; grid-row: 2 / 3; }
<div class="layout-container"> <div id="header">header</div> <div id="bar">bar</div> <div id="main-content">main content</div> </div>
两种方案都能实现目标效果,无需多余的嵌套容器。
内容的提问来源于stack exchange,提问作者baitendbidz
相关产品推荐
相关产品推荐

