在CSS的确切位置显示地图标记

时间:2019-03-01 01:26:02

标签: javascript html css

所以我有一个x和y象限的数据库,并且有一个350x350px的地图。我将地图定位为:

background-image: url(/storage/maps/surface.png);
background-repeat: no-repeat;
height: 350px;
background-position: center center;
margin: 0px auto;
background-size: cover;

宽度似乎是429px,不知道为什么。我确定这与cover有关。

在此图片上方,我有一个标记:

font-size: 32px;
color: #f9e4b4;
z-index: 5;
position: absolute;
top: 78px;
left: 349px;

top代表Y位置,X位置代表left

这些值(topleft)来自数据库,并在React JS中设置。

按现状,它会创建三个div:

<div class="location-map mb-3">
    <div style="background-image: url(&quot;/storage/maps/surface.png&quot;); background-repeat: no-repeat; height: 350px; background-position: center center; margin: 0px auto; background-size: cover;">
        <i class="fas fa-map-marker-alt player-icon" style="top: 78px; left: 349px;"></i>
    </div>
</div>

我遇到的问题是:

enter image description here

如您所见,我正在尝试将此标记放置在地图上像素完美的位置。

现在您看到的位置状态为349, 78,虽然这可能是正确的css明智的做法,但如果标记确实位于左侧349px,则标记应位于地图的边缘(右侧)。

所以我的问题是,图像是否太小?我是否正确放置了图像?为什么标记在原位置而不是我想要的位置?

1 个答案:

答案 0 :(得分:1)

有两个要解决的主要问题:

  1. 地图元素的大小应为精确的350px正方形
  2. 使用topleft应该将图钉的底部放置在精确坐标上。

让我们从地图开始。如果您知道图像的确切图像尺寸,就足够了:

.map {
  background: url(http://placehold.it/350x350);
  height: 350px;
  width: 350px;
}
<div class="map">
</div>

现在,我们可以使用topleft创建要定位的元素到确切像素,通过使用pseudo element允许任何装饰落在可能的位置:

.map {
  background: url(http://placehold.it/350x350);
  height: 350px;
  position: relative;
  width: 350px;
}

.map-x-pin {
  background-color: black; /* So we can see where the pixel is */
  height: 1px;
  position: absolute;
  width: 1px;
}

.map-x-pin::after {
  background-color: red; /* Decorative, this could be an image too */
  bottom: 100%;
  content: '';
  display: block;
  left: -10px; /* Half of the width, give or take a pixel */
  position: absolute;
  height: 40px;
  width: 20px;
}
<div class="map">
  <div class="map-x-pin" style="top: 78px; left: 349px;"></div>
</div>