moople
moople

Reputation: 81

How to fix a DIV in position against an SVG Background?

I have a very simple webpage that I'm trying to construct. It has an img tag including an SVG image file that scales to 100% of the page's width. I also have a collection of DIVs that I'd like to "fix" in place relative to the image.

I started with absolute positioning using ems, but realized quickly that I'd have to move to percents if I wanted the divs to stay in place relative to the scaling background.

But then I realized that the problem is that because my SVG scales due to changes in width of the page, I can't set a good height percentage because height may or may not be affected when the window's width changes due to the SVG's aspect ratio.

Any suggestions on an approach? I'm feeling like I'm missing something basic here.

Here's an example of my page:

<html>
<head>
<style>
    .box{
        width: 4.0em;
        height:3.0em;
        background-color: yellow;
        position: absolute;
    }
    #a{ left:6.4%; top:16.0%; }
    #b{ left:6.4%; top:23.0%; }
    /* This doesn't work. The DIVs aren't fixed relative to bg.svg. */
</style>
<body>
    <img src="bg.svg" width="100%" />
    <div class="box" id="a"></div>
    <div class="box" id="b"></div>
</body>

Upvotes: 1

Views: 4062

Answers (1)

set a an identical top and a left position for .box and img, this way both divs and image have the same 'anchor' point, and you can position the divs relative to that anchor point.

img {
   position: absolute;
    top: 0px;
    left: 0px;
}
.box{
    width: 4.0em;
    height:3.0em;
    background-color: yellow;
    position: absolute;
    top: 0;
    left: 0;
}
#a{ left:20px; top:20px; }
#b{ left:20px; top:20px; }

see it here: http://jsfiddle.net/SebastianPataneMasuelli/hP6Dg/1/

Upvotes: 1

Related Questions