Search code examples
javascripthtmlcsspng

Layering PNG in HTML/CSS?


I want to make an interactive map of the world using HTML, CSS, and JS. Using SVG was probably the recommended way to go, but to be honest I have no experience in utilizing it. Plus editing paths for doing minor changes is a pain. I really prefer exporting each country as a PNG image, placing them in HTML, and JS will handle all the interaction.

It's really easy in concept. The problem however is that how to layer these different PNGs so that each countries will be on its specific place? If you use two <img src=... it would either put the images into a column or a row:

This is how it should be How it should be

But this is how it will show up in HTML enter image description here

or this enter image description here

  • Are there any ways I could stack these images together without putting them into a column or row?
  • If not, is it possible to track a cursor's position within an image? If putting the countries individually on a PNG won't work, I'm planning to export the whole map of the world into one PNG and then monitor what is the cursor's position when clicking the image so I could get the specific country the user clicked on. Is that possible?

Forgive me for being too naive of this. Thanks a ton!


Solution

  • As @rotateDev said, absolute positioning each images with proper offset is the best solution if you are decided to go with PNG images. But clicking on each country will definitely be an issue because of the random shapes of the countries.

    A solution for this is implement countries as background image of individual <DIV> and place a label inside the div with country name. Only this labels will be clickable.

    HTML Sample

    <div class="country gernany">
       <a href="#">Germany</a>
    </div>
    <div class="country france">
       <a href="#">France</a>
    </div>
    <div class="country italy">
       <a href="#">Italy</a>
    </div>
    

    CSS sample:

    .germany{
       .background-image: url(germany.png);
    }
    .germany.active{
       .background-image: url(germany-active.png);
    }
    

    We can use JavaScript to append some class to the <DIV> on the hover or click of the label so we can highlight the country on hover of the label.

    <script>
    $('.country').click(function(){
       $(this).addClass('active');
    });
    </script>