Search code examples
javascripthtmlcsspositioning

What is the best way to position <div> markers over a base image and allow for resize?


I have a underlay.jpg in a <div id=underlay> that I want to precisely place markers on. What is the best way to do this?

I'd like the image to fill the space of the div and markers to adjust when the window is resized. I'm assuming doing it in CSS would be the easiest but I'm not sure.

By the way, I'm generating the markers divs using Javascript. Here is my current code, which doesn't adjust correctly when I resize:

<div id="underlay">
  <img style="height:auto; width:auto; max-width:100%;" src="underlay.jpg">
   <div id="markers">
      <div id="marker1" style="left:36%; top:56%; position:absolute;">"1"</div>
      <div id="marker2" style="left:45%; top:76%; position:absolute;">"2"</div>
      <div id="marker3" style="left:24%; top:65%; position:absolute;">"3"</div>
  </div>
</div>

Solution

  • Here is a little step-by-step tutorial to achive this.

    1. Shrink the container size ( #underlay ) to the image by using display: inline-block. Also add position: relative.

    2. Set the markers container ( .markers ) to position: absolute and set the container dimensions by either using height: 100%; width: 100% or top: 0; right: 0; bottom: 0; left: 0;.

    3. Translate the marker contents to the center of the markers position: transform: translateX(-50%) translateY(-50%);.

    #underlay {
      display: inline-block;
      position: relative;
    }
    
    #underlay>img {
      height: auto;
      max-width: 100%;
      width: auto;
    }
    
    #underlay>.markers {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
    
    #underlay>.markers>.marker {
      position: absolute;
    }
    
    #underlay>.markers>.marker>.marker-content {
      -webkit-transform: translateX(-50%) translateY(-50%);
      -moz-transform: translateX(-50%) translateY(-50%);
      -ms-transform: translateX(-50%) translateY(-50%);
      -o-transform: translateX(-50%) translateY(-50%);
      transform: translateX(-50%) translateY(-50%);
    }
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>
    
    <div id="underlay">
      <img src="https://dailykitten.com/wp-content/uploads/2015/04/image17.jpg" />
      <div class="markers">
        <div id="marker1" class="marker" style="left:40%; top:50%;"><i class="marker-content fa fa-arrow-circle-down" style="color:white"></i></div>
        <div id="marker2" class="marker" style="left:60%; top:42%;"><i class="marker-content fa fa-arrow-circle-down" style="color:white"></i></div>
      </div>
    </div>

    DEMO: http://jsfiddle.net/31480m7n/14/