No need to use Javascript, this can be done in CSS.
The required HTML: (you must change the div to an img obviously)
<div id="container">
<div id="imgwrapper">
<div id="img">Change this div-tag to an img-tag</div>
</div>
</div>
The required CSS:
#container
{
position: absolute;
left: 200px;
top: 100px;
height: auto;
overflow: visible;
border: 2px dashed green;
}
#imgwrapper
{
position: relative;
margin-left: -50%;
margin-top: -50%;
padding-top: 25%;
border: 2px dashed blue;
}
#img
{
display: block;
width: 200px;
height: 100px;
border: 2px solid red;
}
Click here for a jsFiddle link
The margin-left: 50%;
obviously works when using the container div, because the width of the container will be exactly that of the content. (You might need to add width: auto;
)
But margin-top: -50%;
will not work because the height of the container div will change with it, thus you need yet another wrapper div in which you use this margin-top: -50%;
and then you need to fix this error it makes by using a positive percentage based padding. Obviously there may be other solutions to fix this, but the solution should be something like this.