I want to center a div inside a parent div. The only way I can do it is by using margin-left property. The formula is:
margin-left = (parent.width/2) - (child.width/2)
but I can’t get it done via JavaScript because of two things:
-
The width isn’t defined in the style thus cannot be accessed via
document.getElementById("child").style.width -
document.getElementById("child").offsetWidthdoesn’t give the proper and the correct width for unknown reasons
I am using this code, but as said above, it doesn’t work
<script type="text/javascript">
document.getElementById("fb_share").style.marginLeft = parseInt((document.getElementById("vss_border").offsetWidth / 2) - (document.getElementById("fb_share").offsetWidth / 2)) + "px";
</script>
If there is any other solution via CSS (but it must be margin-left and no width change) please tell.
I found your problem. The child width is set to 691px, so once it tries to center the fb_share div it only sets it by a few pixels.
All you have to do is set the style, e.g:
Breakdown
Nothing wrong with your javascript.
The child is almost the same width as the parent, causing a minimum center.
Set the child width correct and all should be working fine