Home > Mobile >  How can I make links maintain position relative to the background image when window resizes?
How can I make links maintain position relative to the background image when window resizes?

Time:03-23

I am wanting to create a map with clickable buttons over the different countries. I have setup a test on https://codepen.io/DigitalDesigner/pen/vYpXvZb I have tried absolute positioning but that causes the link to move off the desired spot.

How can I make the link stay in place when the window expands and contracts?

.europe-map {
  
}
.map-container {
  width:100%;
  height:604px;
}
@media screen and (min-width:768px) {
  .map-container {
    height:727px;
  }
}
.map {
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/6/66/Blank_map_of_Europe_cropped.svg);
      background-size: 100%;
      background-repeat: no-repeat;
  background-position: left top;
      height:100%;
} 
.links {
  
}
.link {
  
}
<section >
  <div >
    <div >
      
    <div >
      <a  href="#" style="position:absolute;left:10%;top:20%;">Test</a>
    </div>
    </div>
  </div>
</section>

CodePudding user response:

One solution - perhaps the most reliable - is to merge the map and the links into their own SVG.

.map-container {
  width: 100%;
  height: 604px;
}

@media screen and (min-width:768px) {
  .map-container {
    height: 727px;
  }
}

.link {
  font-size: 10px;
  text-decoration: underline;
  fill: blue;
}
<section >
  <div >
    <svg viewBox="0 0 593 606" >
       <image xlink:href="https://upload.wikimedia.org/wikipedia/commons/6/66/Blank_map_of_Europe_cropped.svg"/>
       <a  xlink:href="#"> <text x="10%" y="14%">Test</text> </a>
    </svg>
  </div>
</section>

CodePudding user response:

Absolute position is with respect to the nearest positioned element. In this case, you can either eliminate the links element or size it to match the map, then set relative positioning on the parent of the link elements.

Note that I've set the map element's height to the aspect ratio of the image (593/606) using padding, and that I'm shifting the links up and left 50% of their size to center them on the position. The latter resolves apparent movement due to the link size relative to the image size.

.map {
  position: relative;
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/6/66/Blank_map_of_Europe_cropped.svg);
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: left top;
  padding-bottom: 97.85%; /* image width / height */
}

.link {
  position: absolute;
  transform: translate(-50%, -50%); /* center the element on the position */
  text-decoration: none;
  font-family: Arial, sans-serif;
  color: maroon;
}
<section >
  <div >
    <div >
      <a  href="#" style="left:11.4%; top:13.5%;">Iceland</a>
    </div>
  </div>
</section>

  • Related