PROBLEM :

The problem is,

Best way to center a <div> element on a page both vertically and horizontally?

Basically, margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?

SOLUTION 1: 

This solution is the best and most flexible way for center a div ( css center div)

You can check the demo on dabblet.com

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

This trick will work with any sizes of div.

[pastacode lang=”markup” manual=”%3Cdiv%3E%3C%2Fdiv%3E” message=”HTML Code” highlight=”” provider=”manual”/] [pastacode lang=”css” manual=”div%20%7B%0A%20width%3A%20100px%3B%0A%20height%3A%20100px%3B%0A%20background-color%3A%20red%3B%0A%0A%20position%3A%20absolute%3B%0A%20top%3A0%3B%0A%20bottom%3A%200%3B%0A%20left%3A%200%3B%0A%20right%3A%200%3B%0A%0A%20margin%3A%20auto%3B%0A%7Dc” message=”CSS Code” highlight=”” provider=”manual”/] [ad type=”banner”]

SOLUTION 2: 
It is the another Simplest technique to center a div ( css center div) (This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it’s just fine.)

Markup:

[pastacode lang=”markup” manual=”%3Cdiv%3EWelcome%20to%20wikitechy.com%3C%2Fdiv%3E” message=”HTML Code” highlight=”” provider=”manual”/] [pastacode lang=”css” manual=”div%20%7B%0A%20background%3Ared%3B%0A%20position%3Aabsolute%3B%0A%20color%3A%23fff%3B%0A%20top%3A50%25%3B%0A%20left%3A50%25%3B%0A%20padding%3A15px%3B%0A%20-ms-transform%3A%20translateX(-50%25)%20translateY(-50%25)%3B%0A%20-webkit-transform%3A%20translate(-50%25%2C-50%25)%3B%0A%20transform%3A%20translate(-50%25%2C-50%25)%3B%0A%7D%20%0A” message=”CSS Code” highlight=”” provider=”manual”/]

This will center element horizontally and vertically too. No negative margins, just power of transforms.

[ad type=”banner”]

SOLUTION 3: 

In this solution, there are two ways to to center a div ( css center div) through CSS.

[pastacode lang=”css” manual=”.middleDiv%20%7B%0A%20position%20%3A%20absolute%3B%20%0A%20width%20%3A%20200px%3B%0A%20height%20%3A%20200px%3B%0A%20left%20%3A%2050%25%3B%0A%20top%20%3A%2050%25%3B%0A%20margin-left%20%3A%20-100px%3B%20%2F*%20half%20of%20the%20width%20*%2F%0A%20margin-top%20%3A%20-100px%3B%20%2F*%20half%20of%20the%20height%20*%2F%0A%7D” message=”CSS Code” highlight=”” provider=”manual”/]

Categorized in: