Not being a web guy I don’t know all the quirks of HTML. I am attempting to center some dynamically sized content inside of a div. This content should always be centered, so I hooked into window.resize to do it. I then manually call window.resize() after applying the CSS to force it to run once.
The problem is that the div does not center horizontally at first, only vertically. Subsequent window resizes force the div to center properly.
Initially I thought that I must be trying to center the div before it was ‘ready’ as I am calling it first before document.ready fires, but the vertical centering works and I added some trace statements and, sure enough, the left position is being calculated correctly, just not applied (seemingly).
Anyway, this is my first real foray into HTML+CSS, so I’m sure you guys will nail it quickly. Here is some sample html and javascript which reproduces the problem.
Also, my testing has been in Chrome exclusively thus far.
<html lang="en-US">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(window).resize(function() {
var win = $(window);
var area = $('#signuparea');
$('#signuparea').css({
position: 'absolute',
left: (win.width() - area.outerWidth()) / 2,
top: (win.height() - area.outerHeight()) / 2
});
//$('body').append('<div>l=' + ((win.width() - area.outerWidth()) / 2) + '</div>');
//$('body').append('<div>w=' + area.outerWidth() + '</div>');
//$('body').append('<div>h=' + area.outerHeight() + '</div>');
});
$(window).resize();
});
</script>
</head>
<body style="background-color:0000FF">
<div id="signuparea">
<input type="password">
</div>
</body>
</html>
What about using this code in your
window.resizeevent handler:Since three of the properties set above are static they can be set in CSS:
Which makes your JS look like this:
Here is a jsfiddle of this solution: http://jsfiddle.net/jasper/Ty6Af/2/