I have written a jQuery function to dynamically center my <div>
element. It seems to work fine when the page loads, but fails to re-center on window resize.
Can anyone spot what I might be doing wrong?
JS:
<script>
$( document ).ready(function() {
function reCenter() {
$('.content').css({
position:'absolute',
left: ($(window).width()
- $('.content').outerWidth())/2,
top: ($(window).height()
- $('.content').outerHeight())/2
});
}
$(window).resize(reCenter());
// To initially run the function:
reCenter();
});
</script>
HTML:
<div class="content">
<h1>Header</h1>
<span class="hyphen">-</span>
<h2>Subtext</h2>
</div>
CSS:
* {
padding: 0;
margin: 0;
}
html {
background: darkgrey;
}
body {
color: #fff;
text-align: center;
/*padding-top: 300px;*/
}
h1 {
font-family: 'Arimo', sans-serif;
text-transform: uppercase;
font-weight: bold;
font-size: 40px;
}
span.hyphen {
color: #0CFFFC;
font-size: 3em;
}
h2 {
font-family: 'Montserrat', sans-serif;
font-weight: 100;
}
UPDATE
Despite successfully triggering the function on page load, it doesn't behave consistently between initial load and window resizing.
http://jsfiddle.net/7zqkd4w8/