css HTML

[Solved – 3 Answers] Best way to center a <div> on a page vertically and horizontally?

[Solved - 3 Answers] HTML - css center div - Best way to center a element on a page both vertically and horizontally? Basically, margin-left:

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.

HTML Code
<div></div>
CSS Code
div {
 width: 100px;
 height: 100px;
 background-color: red;

 position: absolute;
 top:0;
 bottom: 0;
 left: 0;
 right: 0;

 margin: auto;
}c

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:

HTML Code
<div>Welcome to wikitechy.com</div>
CSS Code
div {
 background:red;
 position:absolute;
 color:#fff;
 top:50%;
 left:50%;
 padding:15px;
 -ms-transform: translateX(-50%) translateY(-50%);
 -webkit-transform: translate(-50%,-50%);
 transform: translate(-50%,-50%);
} 

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

SOLUTION 3: 

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

CSS Code
.middleDiv {
 position : absolute; 
 width : 200px;
 height : 200px;
 left : 50%;
 top : 50%;
 margin-left : -100px; /* half of the width */
 margin-top : -100px; /* half of the height */
}
READ  [Solved - 5 Answers] CSS - HTML - How to center absolutely positioned element in div

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment