精确的文本覆盖在图像上(并且响应迅速)



我想把文本放在图片上的特定位置。此文本必须相对于图像保持在同一位置。我举了这个简单的例子来说明这个问题。60kg必须位于材料旁边。如果我稍微调整浏览器的大小,文本就会移动,不再位于材质旁边。这就是它应该是什么样子(即使在调整大小时(:示例

.background {
background-color: lightgrey;
position: relative;
}
.crane {
width: 30vw;
margin-left: 35vw;
position: absolute;
}
.overlay {
background-color: rgb(255, 0, 0, 0.5);
position: absolute;
margin-left: 43vw;
margin-top: 37vh;
width: auto;
font-size: 1em;
padding: 2px;
}
<div class="background">
<img class="crane" src="https://img.freepik.com/free-vector/isolated-tower-crane-cartoon-style_1308-104645.jpg?w=2000" 
class="img-responsive">
</div>
<div class="overlay">
60kg
</div>

不要定位图像,而是使用百分比而不是绝对值来定位文本。

.background {
background-color: lightgrey;
position: relative;
display: inline-block;
height: 100vh;
}
.crane {
max-width: 100%;
height: 100%;
}
.overlay {
background-color: rgb(255, 0, 0, 0.5);
position: absolute;
left: 30%; /* adjust as required */
top: 52%; /* adjust as required */
width: auto;
font-size: 1em;
padding: 2px;
}
<body>
<div class="background">
<img class="crane" src="https://img.freepik.com/free-vector/isolated-tower-crane-cartoon-style_1308-104645.jpg?w=2000" class="img-responsive">
<div class="overlay">
60kg
</div>
</body>

因为不可能在图像中创建子元素,所以需要将图像与共享容器对齐。如果我们谈论两个div,我们可以做一些简单的事情,比如:

<div id="container">
<div id="child"></div>
</div>
#container {
position: relative;
border: 2px solid red;
width: 10rem;
height: 10rem;
}
#child {
position: absolute;
top: 20%;
left: 20%;
border: 2px solid blue;
width: 2.5rem;
height: 2.5rem;
}

JSFiddle


因为我们的元素之一是图像,所以我们需要采取另一种方法。我们的文本和起重机图像都应该有absolute定位。容器需要有一个relative位置。我们需要创建一个共享容器。然后,我们可以用绝对位置(顶部、底部、左侧、右侧(指定我们希望文本相对于图像的方式。我们应该使用百分比而不是绝对值。

它可以这样实现:

请注意,我使用flex容器创建了一个响应友好的设计。

<body>
<div class="flex-container">
<div class="background">
<img class="crane" src="https://img.freepik.com/free-vector/isolated-tower-crane-cartoon-style_1308-104645.jpg?w=2000" class="img-responsive">
<div class="overlay">
60kg
</div>
</div>
</body>
.flex-container {
display: flex;
justify-content: center;
}
.background {
background-color: lightgrey;
position: relative;
}
.crane {
width: 30vw;
position: relative;
}
.overlay {
background-color: rgb(255, 0, 0, 0.5);
position: absolute;
font-size: 1em;
padding: 5px;
left: 30%;
top: 50%;
}

您可能还想添加一些媒体查询以使其更准确:

@media only screen and (min-width: 800px) {
.overlay {
top: 52%;
}
}

JSFiddle

最新更新