Search code examples
jqueryhtmlcssvertical-alignment

Align element horizontally and vertically to the center of the page


It's been long time that I don't make a website and I can't remember how to align vertically a div in a proper way. I checked many online resources and also stackoverflow questions but nothing helped or at least I didn't see where my mistake is.

I created a text that at the beginning is hidden and after some time appears and scales getting bigger using jQuery. It seems to work and it is centered horizontally but not vertically. How to align it vertically to the center of the page?

HTML

<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<link href="main.css" rel="stylesheet" />
<title>Homepage</title>
<script src="jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="container" align="center">
<p id="robo">ROBO</p>
</div>
<script>
$(document).ready(function() {
    $("#robo").delay(500).fadeIn(500).animate({fontSize: "3em"}, 1000);
}); 
</script>

</body>
</html>

CSS

*{
    margin: 0px;
    padding: 0px;
}
body {
    text-align: center;
    width: 100%;
}
#container {
    width: 1024px;
    height: 768px;
    margin: 0 auto;
}
#robo {
  display:none;
  width:200px;
  height:200px;
}

JSFiddle Example: http://jsfiddle.net/sMrL9/


Solution

  • Using CSS

    The link below provides five methods for vertical centering, the pros and cons of each, and how to implement each one. I recommend reviewing the page.

    http://www.vanseodesign.com/css/vertical-centering/

    Using jQuery

    This SO answer provides a dynamic jQuery solution.

    Working Fiddle: http://jsfiddle.net/sMrL9/1/

    jQuery.fn.verticalAlign = function ()
    {
        return this
                .css("margin-top",($(this).parent()
                .height() - $(this).height())/2 + 'px' )
    };
    
    $(document).ready(function() {
        $("#robo").delay(500)
                  .fadeIn(500)
                  .animate({fontSize: "3em"}, 1000)
                  .verticalAlign();
    });
    

    Other possible solutions: