我有一个图像,遗憾的是它不能用作背景图像,顶部有一个文本框。它可以工作,但它没有响应,使用bootstrap 4.当我达到较小的屏幕尺寸时,文本框超出了图像。
在初始大小它很好,但一旦你缩小页面,文本框就会弹出。这是HTML:
<div class="container-fluid something-container">
<div class="row">
<img class="img-responsive something-img" src="http://placehold.it/900x100"/>
<div class="container">
<div class="row something-front d-flex justify-content-center">
<div class="col-sm-8 something-text text-center">
<h1>Header</h1>
<p>Here are some words but typically a lot more are present here.</p>
</div>
</div>
这是CSS:
.something-container{
position:relative;
text-align: center;
}
.something-img{
width: 100%;
}
.something-text{
position: absolute;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.7);
color: white;
p {
line-height: 2em;
padding-left: 10px;
}
h1 {
text-transform: uppercase;
font-weight: 550;
padding-top: 20px;
}
}
我创建了一个CodePen来显示它:CodePen
如何让该文本框保留在图像中?
像.image-wrapper
一样在包装div中包装你的图像和文本,如下所示:
<div class="container-fluid something-container">
<div class="row">
<div class="container">
<div class="row something-front d-flex justify-content-center">
<div class="image-wrapper">
<img class="img-responsive something-img" src="http://placehold.it/900x100" />
<div class="col-sm-8 something-text text-center">
<h1>Header</h1>
<p>Here are some words but typically a lot more are present here.</p>
</div>
</div>
</div>
</div>
</div>
</div>
CSS:
.image-wrapper {
width: 900px;
height: 100px;
position: relative;
margin: 0 auto;
}
.something-img {
width: 100%;
height: auto;
}
.something-text {
position: absolute;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.7);
color: white;
height: 90%;
}
这为定位父元素提供了工作,您可以独立地设置图像和文本的样式,同时保持框尺寸相同/响应。字体大小必须随着大小的增加/缩小而改变以保持在框中,但文本将以图像为中心。