简体   繁体   中英

Keep divs positioned relative to image

I am trying to create a "map" with divs over cities. I got the map in .svg format and using it as background with background-size: cover. I need the "city-divs" to stay positioned relative to the image (for example London div should be always over London position on my image). I can half-achieve this making the "city divs" absolute and then positioning it using vh and vw. However, if I resize the window or check on different computer, it messes up.

I guess pure css is not the correct way on doing this. Is there a way of achieving this or am I going completely wrong direction?

Closest I got was using this solution found on stackoverflow http://jsfiddle.net/fmenrd4z/ . This works for divs in the center of image just about right. Divs more to the left / right won't work as good.

Currently, I'm using this code.

HTML

<section id="map">
  <div id="london">london</div>
  <div id="paris">paris</div>
</section>

CSS

#map {
    background-image: url(../img/maps/map.svg);
    width: 100vw;
    height: 90vh;
    background-attachment: fixed;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}

#london {
    position: absolute;
    left: 31vw;
    top: 35vh;    
}
#paris {
    position: absolute;
    left: 60vw;
    top: 73vh;    
}

I suppose there must be solution for this problem. I've been searching the web for whole day today but didn't found anything.

I'm up for choosing completely different way of doing this. (Is there some javascript library etc..?) Thanks in advance!

This will never work because you position the divs dimensions that are always changing depending on the screen it is displayed.

There is one of way of doing it by giving a fixed height and width of section #map in pixels for large screens and adding some media queries for mobile screens.

#map {
    width: 600px;
    height: 300px;
}

@media (max-width: 1024px){
    #map {
        width: 300px;
        height: 150px;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM