#hero-container {
display: flex;
position: relative;
height: 520px;
}
.hero {
position: absolute;
left: 0;
top: 0;
}
#text {
z-index: 100;
position: absolute;
color: white;
font-size: 3vw;
font-weight: bold;
left: 150px;
top: 40px;
}
#text2 {
z-index: 100;
position: absolute;
color: white;
font-size: 2vw;
font-weight: bold;
left: 150px;
top: 70px;
}
#hero-container img {
display: flex;
width: 100%;
}
<html>
<head>
</head>
<body>
<div id="hero-container">
<img class="hero" src="https://vreauperle.ro/images/banners/hero-image.jpg"></img>
<p id="text">
First text here
</p>
<p id="text2">
Secondary
</p>
</div>
</body>
</html>
我在固定容器中有一张 width:100% 的图片。因为我的图像调整了大小,文本没有跟随并保持在相同的位置,因此移动到容器上。
如何在不添加 1000 个媒体查询的情况下使文本保持在图像的中心(垂直)和左侧,并填充几个像素(水平)?
最佳答案
您可以大大简化您的 CSS:
- 移除 flex(除非有某些特定原因您需要它)。
- 将您想要垂直居中的文本包裹在
div
和translateY(-50%)
中。 - 确保图像周围的包装器具有
position:relative
。
#hero-container {
position: relative;
}
#center-text {
z-index: 100;
position: absolute;
color: white;
font-weight: bold;
left: 15%;
top: 50%;
transform: translateY(-50%);
}
#text {
font-size: 3vw;
margin: 0;
}
#text2 {
font-size: 2vw;
margin: 0;
}
#hero-container img {
width: 100%;
height: auto;
}
<div id="hero-container">
<img class="hero" src="https://vreauperle.ro/images/banners/hero-image.jpg" />
<div id="center-text">
<p id="text">
First text here
</p>
<p id="text2">
Secondary
</p>
</div>
</div>
无论您的分辨率如何,这都将完全响应,并且应该在 IE10+(或带有 -ms-transform
前缀的 IE9+)中工作,如果您使用一些更标准的字体大小(而不是 vw
).
关于html - 在可缩放图像上定位文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001412/