Center DIV Horizontally and Vertically

199 views Asked by At

I have this HTML structure:

<div class="metaboxdet">
    <div class="metd">
        <h1>Hello World!</h1>
    </div>
</div>

http://jsfiddle.net/fvueL00n/2/

the problem here is I cant center the div "metd" horizontally and vertically. I have tried adjusting the top, bottom, left and right but it return a not so accurate results. Is there a way where i can center horizontally and vertically dynamically.

please check the fiddle here to see it in action. Thanks!

4

There are 4 answers

0
Billy On BEST ANSWER

As discussed in this answer, you can add a helper element with height:100% and display:inline-block with vertical-align:middle, and change the container to be display:inline-block with vertical-align:middle

.helper{
    display:inline-block;
    height:100%;
    vertical-align:middle;
}
/*container*/
.metd{
    vertical-align:middle;
    display:inline-block;
}

Here's the code in action

2
potashin On

You can use table layout (you should also apply display:table; to the .metaboxdet container):

.metd {display:table-cell;vertical-align:middle }

JSFiddle

2
Achrome On

You can use a flexbox, but it will not support older browsers.

.metaboxdet {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
}

Vendor prefixes are left for the reader to add for completeness.

0
Arpit Goyal On

edited your markup to:

<div style="display:table;" class="metaboxdet">
  <div style="display:table-cell;vertical-align:middle;" class="metd">
    <div style="margin-left:auto;margin-right:auto;">
        <h1>Hello World!</h1>
    </div>
  </div>
</div>

and your css is unchanged you can remove not needed css:

.metaboxdet {
    height: 100%;
    width: 100%;
    position: absolute;
    right: 0;
    top: 0;
    z-index:9;
    text-align:center;
    margin:0px auto;
    background-color: #292484;
    background-image: linear-gradient(135deg, #292484, #dc4225);
    opacity: 0.6;
}

.metd {position:relative; margin:0px auto; width:70%; }
.metd h1 {color: #FFF; font-size:40px; font-style:italic; text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); line-height:1.2em;}

or check this I've edited you fiddle to this

https://jsfiddle.net/fvueL00n/2/

and if you don't want there that extra div you can align h1 directly in div as well

for more refer howtocenterincss.com