A lot of people have this problem and I've just recently saw a thread about this, but dead-centering elements in HTML seems to be a struggle when it shouldn't be so I decided to write a little work-around for it.
There are probably many of these sorts of scripts and I've also saw work-arounds where people will wrap the element in 2 divs that will position it from the top and the 2nd div will position it from the left.
This script simply takes every element with the class of 'deadcentre' then it will take it's parent element, get the height and width of it, subtract the outer-height and outer-width from the parent elements and then divide by 2 to get it slap bang in the centre.
Script below:
Before deadcentre:
After deadcentre:
Hope it helps, fuckers.
- Mark
There are probably many of these sorts of scripts and I've also saw work-arounds where people will wrap the element in 2 divs that will position it from the top and the 2nd div will position it from the left.
This script simply takes every element with the class of 'deadcentre' then it will take it's parent element, get the height and width of it, subtract the outer-height and outer-width from the parent elements and then divide by 2 to get it slap bang in the centre.
Script below:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Dead Centre</title>
<style type="text/css">
#div1 {
height: 500px;
width: 700px;
background: #dedede;
}
#div2 {
height: 300px;
width: 450px;
background: #de17fd;
}
</style>
</head>
<body>
<div id="div1">
<div id="div2" class="deadcentre"></div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
$('.deadcentre').each(function(i, a) {
$parent = $(a).parent();
$(a).css({
position: "relative",
top : ($parent.height() - $(a).outerHeight())/2,
left : ($parent.width() - $(a).outerWidth())/2
});
});
});
</script>
</body>
</html>
Before deadcentre:
After deadcentre:
Hope it helps, fuckers.
- Mark