Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CSS, how to scale multiple overlayed images responsively?

I have multiple images overlayed on top of a background, here's an example:

<div style="position: relative; left: 0; top: 0;">
    <img src="images/background.png" style="position: relative; top: 0px; left: 0px;"/> 
    <img src="images/overlay1.png" style="position: absolute; top: 20px; left: 20px; "/>
    <img src="images/overlay2.png" style="position: absolute; top: 40px; left: 40px; "/>
</div>

The above snippet works if the browser is in full screen mode. If I reduce the browser size, only the background.png is scaled accordingly, but overlay1.png and overlay2.png both remained the same size fixed at their positions. I tried changing the all position attributes to relative but the overlay images are appearing in the wrong spots.

How would I refactor this to allow all images within a div tag to scale properly relative to each other? BTW, I am using Twitter Bootstrap 2.3.2 as the default CSS theme.

More info. All images are of fixed size, e.g. the background is 640x480, shown at position 0, 0. The overlay images are also fixed size and need to go into certain positions in relation to the background image. e.g. an overlay maybe 64x64 and goes to position 15, 24 (top, left), another maybe 128x128 and goes into position 200, 231, etc. With these precise position overlaying, the background + the overlays becomes a complete picture.

like image 919
azgolfer Avatar asked Aug 28 '13 16:08

azgolfer


1 Answers

In order to keep everything in scale when resizing the browser window you should use percentage values for both the size and position of the overlays.

In your case everything is fixed so it's just a matter of converting the pixels to percentages, for this you need the simple formula:

% value = px value / container px value * 100

For example, for Overlay 1 size:(64x64) position:(24,15):

width = 64/640*100 = 10%
top = 15/480*100 = 3.125%
left = 24/640*100 = 3.75%

Now just set the overlays to be absolutely position and apply the correct values for each property:

.container {
    position:relative;
    width: 100%;
    max-width: 640px;
    line-height: 0;
}

.container img{
    max-width: 100%;
}

.overlay1{
    width: 10%;
    position: absolute;
    top: 3.125%;
    left:3.75%;
}

.overlay2{
    width: 20%;
    position: absolute;
    top: 41.666%;
    left: 36.09%;
}

Check out the Demo fiddle

like image 120
omma2289 Avatar answered Sep 20 '22 05:09

omma2289