Prasoon
Prasoon

Reputation: 435

Aligning a DIV to vertical centre to a page

Well, I've read many solutions for that but none of that worked properly.

I don't want to align it horizontal-centre, it should be aligned to vertical-centre to page only. Also obviously, page size is dynamic and DIV height is also dynamic.

I've created a jsfiddle at -

http://jsfiddle.net/yesprasoon/mukKB/

You can see height: 200px; in CSS there, and it works well. But what if div size changes?

Upvotes: 1

Views: 2879

Answers (2)

avrahamcool
avrahamcool

Reputation: 14094

Pure CSS solution.

See that Working JSbin

HTML: (just added an empty span, and the comment is important)

<span class="Centerer"></span><!--
--><div class="vertical-centre" id="loginForm">
    <form>
        <div id="welcometext2" style="text-align:center;"><b>Welcome to LC Inventory App</b>
        </div>
        <br />
        <input type="text" name="username" id="username" value="" placeholder="Username" />
        <input type="password" name="password" id="password" value="" placeholder="Password" />
        <input type="submit" value="Login" id="submitButton" />
    </form>
</div>

CSS:

*
{
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
html, body
{
  height: 100%;
}
.vertical-centre
{
    padding: 0 15px;
    width: 100%;
    display: inline-block;
    vertical-align: middle;
}

.Centerer
{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

Upvotes: 1

Milan and Friends
Milan and Friends

Reputation: 5610

jQuery solution, here's a FIDDLE

$(function(){
   var wHgt = $(window).innerHeight(),
       lHgt = $('#loginForm').outerHeight();

   $('#loginForm').css({ top: wHgt/2 - lHgt/2 + 'px' });

   $(window).resize(function(){
      var wHgt = $(window).innerHeight(),
          lHgt = $('#loginForm').outerHeight();
      $('#loginForm').css({ top: wHgt/2 - lHgt/2 + 'px' });
  });
});

Upvotes: 1

Related Questions