Bootstrap 5图片中央添加带白色背景文本的布局问题
解决Bootstrap 5图片中央添加白色背景文本的问题
问题说明
- 白色背景会覆盖整张图片,无法形成包裹文本的白色矩形
- 给
.contact-image-box设置max-width:400px后,标题和文本无法居中对齐
解决方案
针对两个问题,修改.contact-image-box的CSS属性即可:
- 移除让容器占满父元素的
left:0; right:0; top:0; bottom:0;属性,避免背景覆盖整张图 - 使用
top:50%; left:50%; transform: translate(-50%, -50%);实现容器在图片中央定位 - 添加
padding属性,让白色背景能包裹住文本内容 - 保留
max-width:400px限制容器宽度,配合flex布局确保内部文本居中
修改后的代码
CSS代码
.our-company-title { line-height: 31px; letter-spacing: 0; color: #000; font-size: 25px; } .our-company-text { color: #787878; line-height: 150%; font-size: 18px; letter-spacing: 0; } .contact-image-box { position: absolute; background-color: #fff; text-align: center; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 400px; padding: 2rem; display: flex; align-items: center; justify-content: center; flex-direction: column; }
HTML代码
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <div class="container-fluid overflow-hidden"> <div class="row"> <div class="col-12 col-md-6 p-0 position-relative"> <div class="position-relative"> <img class="img-fluid w-100 h-100 object-fit-cover" src="https://via.placeholder.com/300x100" alt=""> <div class="contact-image-box"> <h3 class="our-company-title">Title</h3> <p class="our-company-text">Company text</p> </div> </div> </div> <div class="col-12 col-md-6 align-self-md-center"> content here </div> </div> </div>
关键修改解释
top:50%; left:50%; transform: translate(-50%, -50%);:绝对定位元素居中的标准写法,能让容器精准定位到图片中央,且不受自身宽度影响padding:2rem:给白色背景容器添加内边距,让文本和背景边缘有足够间距,形成美观的白色矩形- 保留
max-width:400px:限制容器最大宽度,避免大屏幕上过度拉伸,flex布局的align-items:center和justify-content:center确保内部文本始终居中
内容的提问来源于stack exchange,提问作者maxteprov7
相关产品推荐
相关产品推荐

