JSFiddle - React, Tailwind, and code Playground
HTML
<img src = "http://fc06.deviantart.net/fs50/f/2009/325/9/e/Super_Mario_Bros__Background_by_Hyp64.png" class = "image"/>
CSS
html, body {
width: 100%;
height: 100%;
margin: 0;
}
img {
height: 100%;
}
JavaScript
$(document).ready(function(){
// graphic array stores all graphics on the page
graphicArr = new Array();
function addGraphic(arr, obj) {
arr.push(obj);
}
function resizeAll(arr) {
for (i = 0; i < arr.length; i++)
arr[i].resize();
}
function PercentageBasedGraphic(left, width, height, bottom, id)
{
// create an object that is associated with the div we will create using the parameters passed
var object={};
object.left = left;
object.width = width;
object.id = id;
object.selector = "#" + id;
var newDiv = document.createElement('div');
// use document.createElement, not jQuery. it's faster http://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
newDiv.setAttribute('id', id);
newDiv.style.position = 'absolute';
newDiv.style.height = height + "%";
newDiv.style.bottom = bottom + "%";
newDiv.style.backgroundColor = "red";
document.body.appendChild(newDiv);
// define a resize function for this object
object.resize = function(){
var imgWidth = $(".image").width();
$(this.selector).css('width', imgWidth*(this.width/100));
$(this.selector).css('left', imgWidth*(this.left/100));
};
object.resize();
return object;
}
// add graphics to the page
addGraphic(graphicArr, PercentageBasedGraphic(25, 10, 4, 30, "block1"));
addGraphic(graphicArr, PercentageBasedGraphic(10, 30, 5, 40, "block2"));
// on page resize, reposition the graphics as needed
$(window).resize(function(){
resizeAll(graphicArr);
});
});