THE AMAZING
THE AMAZING

Reputation: 1603

Center this div

Iv'e been fondling this code for hours and have gained no advil.

Originally i thought, "Hey make a table and vertically transform that piece of ..." but apparently, either i'm a moron that's doing it wrong or.. yeah i'm just an idiot.

<html>
     <head>
          <style type='text/css'>
     html, body{
          margin:0;
          padding:0;
          display:table;
     }
     #centerme{
          display:table-cell;
          vertical-align: middle;
          height:100px;
          width:100px;
     }
     </style>
 </head>
     <body>
          <div id='centerme'></div>
     </body>
</html>

I feel as if something treacherous is missing from this html.

I am not using CSS3 or any 3rd party libraries for CSS _does not work on all browsers

position: relative;
    top: 50%;
    transform: translateY(-50%);

Upvotes: 0

Views: 60

Answers (2)

Anupam Basak
Anupam Basak

Reputation: 1523

Here is an example of vertical centering without using display: table

html, body{
  margin:0;
  padding:0;
}
#centerme{
  height:100px;
  width:100px;
  position: absolute;
  top: 50%;
  margin-top: -50px;  /*  -(height/2)px  */
  border:1px solid;
}
<div id="centerme"></div>

Upvotes: 0

j08691
j08691

Reputation: 208002

If you want both horizontal and vertical alignment, try this:

html, body {
    margin:0;
    padding:0;
}
#centerme {
    height:100px;
    width:100px;
    border:1px solid #999;
    position:absolute;
    margin:auto;
    top:0;
    right:0;
    bottom:0;
    left:0;
}
<div id='centerme'>center</div>

Upvotes: 1

Related Questions