Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a div vertically?

Tags:

html

css

I have a div that I want to center horizontally and vertically.

For the horizontal issue everything is great, but I have a problem with the vertical alignment.

I tried this:

#parent {
    display: table;
}

#child {
    display: table-row;
    vertical-align: middle;
}

but this doesn't work.

like image 345
trrrrrrm Avatar asked Dec 11 '10 09:12

trrrrrrm


3 Answers

If you only have to support browsers that support transform (or its vendor prefixed versions), use this one weird old trick to vertically align elements.

#child {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

If you have to support older browsers, you can use a combination of these, but they can be a pain due to the differences in rendering block vs table.

#parent {
    display: table;
}

#child {
     display: table-cell;
     vertical-align: middle;
}

If your height is fixed and you need to support those really old, pesky browsers...

#parent {
   position: relative;
}

#child {
   height: 100px;
   position: absolute;
   top: 50%;
   margin-top: -50px;
}

If your height is not fixed, there is a workaround.

See it on jsFiddle.

like image 156
alex Avatar answered Oct 25 '22 11:10

alex


Having the parent property as, display:table and child property as display: table-cell and vertical-align: middle worked for me.

like image 22
Abdullah Aman Avatar answered Oct 25 '22 10:10

Abdullah Aman


You can use flexbox to center horizontally or vertically your child div inside a parent div:

This should be your html:

<div id="parent">
   <div id="child">
      info
   </div>
</div>

And this is the css with flexbox:

#parent{
   display: flex;
   align-items: center;
   justify-content: center;
   position: relative;
   width: 100%;
   height: 100vh;
   background: lightgray;
}
#child{
   position: relative;
   background: black;
   padding: 2rem;
   color: white;
   box-shadow: 5px 5px 20px rgba(0,0,0,.4);
   border-radius: 5px;
}

Here is de codepen: https://codepen.io/bongardabo/pen/YzZQgaJ

like image 42
bpardo Avatar answered Oct 25 '22 10:10

bpardo