Best way to center a <div>
element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
Best way to center a <div>
element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
Here is a script i wrote a while back (it is written using the jQuery library):
position: absolute div in body document
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport (body tag), like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
source: CSS position
I think there are two ways to make a div center align through CSS.
This is the simple and best way. for the demo please visit below link:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
I was looking at Laravel's view file and noticed that they centered text perfectly in the middle. I remembered about this question immediately. This is how they did it:
Result looks so:
Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flex or pseudo classes.
You can see an example in the following fiddle. Here is the updated fiddle.
For pseudo classes an example could be:
The usage of display: flex, according to css-tricks and MDN is as follows:
There are other attributes available for flex, which are explained in above mentioned links, with further examples.
If you have to support older browsers, which don't support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.
Adjust left and top with respect to width and height, that is (100% - 80%) / 2 = 10%