如何在h1标签的两行文字之间添加定位文本
优化英雄区布局实现方案
你当前通过大line-height和负margin-top的方式虽能实现效果,但属于hack式写法,维护性差且适配性弱。推荐用Flexbox重构布局,更简洁优雅,代码如下:
优化后代码
HTML
<div class="container"> <div class="overlay"> <h1><span class="first-word">Complete</span><br> Remodeling</h1> <div class="small-flexbox"> <p>With 30 years of experience and a track record of successful projects, we have the skills and expertise to remodel your house with precision, efficiency, and minimal stress for you.</p> <a href="#">Get a Quote</a> </div> </div> </div>
CSS
.container { background-image: url(https://houniqueconstruction.com/wp-content/uploads/2023/02/kam-idris-_HqHX3LBN18-unsplash-scaled.jpg); background-position: bottom left; background-repeat: no-repeat; background-size: cover; min-height: 600px; /* 用min-height适配内容 */ } .overlay { min-height: 600px; width: 100%; background-color: rgba(0,0,0,0.4); display: flex; /* 用Flex做垂直布局 */ flex-direction: column; justify-content: center; /* 垂直居中整体内容 */ align-items: center; padding: 2rem; box-sizing: border-box; } .small-flexbox { display:flex; justify-content:center; align-items:center; max-width:1200px; gap: 3em; /* 用gap替代margin-right,更规范 */ margin-top: 2rem; /* 用正margin控制间距,清晰可控 */ } h1, p, a {color:white;} h1 { text-align:center; font-size:80px; letter-spacing:5px; text-transform:uppercase; line-height: 1.2; /* 合理行高,避免多余空白 */ margin: 0; } a { border:15px solid #f5e2c8; padding:10px 30px; text-transform:uppercase; text-decoration: none; } .first-word { letter-spacing:11px; } p { max-width:400px; margin: 0; }
优化说明
- 给
.overlay设置display: flex并指定垂直方向布局,通过justify-content: center实现内容垂直居中,彻底告别负margin和大line-height的hack - 用
gap替代margin-right控制文本和按钮的间距,布局逻辑更清晰 - 将固定
height改为min-height,提升响应式适配能力 - 给
h1设置合理的line-height:1.2,避免多余的垂直空白,同时移除不必要的padding-top和display:block - 将内联样式移到CSS中,保持代码结构统一
内容的提问来源于stack exchange,提问作者John Holliday
相关产品推荐
相关产品推荐

