1

As the title implies, I need to know how to center a div that has the following CSS rules applied to it:

display: table;
position: absolute;

The div should be right in the middle of the viewport, and, as per usual with display: table;, it should be the size of it's contents.

  • possible duplicate of [Best way to center a
    on a page vertically and horizontally?](http://stackoverflow.com/questions/356809/best-way-to-center-a-div-on-a-page-vertically-and-horizontally)
    – Paulie_D Feb 01 '14 at 14:02
  • Nah, it's different with `display:table`, because it makes the div not vertically centered, but rather, top-aligned. – user3260509 Feb 01 '14 at 14:03

1 Answers1

1

HTML

<div class="center"></div>

If the table has a fixed height and width of 400px then you can use this css:

.center {
    display:table;
    position:absolute;
    height:400px;
    width:400px;
    background:red;
    left:50%;               
    margin-left:-200px;     <---- half of width
    top:50%;                
    margin-top:-200px;      <---- half of height
}

DEMO WITH CSS

If the table has a dynamic height and/or dynamic width then you can use this jquery:

$('.center').css({
    'left': $(window).width() / 2 - $('.center').width() / 2,
    'top': $(window).height() / 2 - $('.center').height() / 2
});

DEMO WITH JS

Pedro Estrada
  • 2,384
  • 2
  • 16
  • 24