What's the best way to center < div > elements vertically and horizontally on a page?
I know that margin left: Auto; margin right: Auto; margin left: Auto; margin right: Auto; will be centered horizontally, but what's the best way to do it vertically?
#1 building
This solution works for me
.middleDiv{ position : absolute; height : 90%; bottom: 5%; }
(or height: 70% / bottom: 15%
Height: 40% / bottom: 30%...)
#2 building
The best, the most flexible way
The main technique of this demonstration is that the normal flow of elements is from top to bottom, so margin top: Auto is set to zero. However, absolutely placed elements have the same role in allocating free space, and can similarly be vertically centered at the specified top and bottom (not in IE7).
This technique is applicable to div s of any size.
div { width: 100px; height: 100px; background-color: red; position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto; }
<div></div>
#3 building
I think there are two ways to align the div center through CSS.
.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 */ }
This is the easiest and best way. For a demonstration, visit the following link:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
#4 building
Even if it doesn't work when the OP raises this issue, I think the best solution, at least for modern browsers, is to use display: flex or pseudo classes.
You can find Violin See an example. This is Updated violin .
For pseudo classes, an example might be:
.centerPseudo { display:inline-block; text-align:center; } .centerPseudo::before{ content:''; display:inline-block; height:100%; vertical-align:middle; width:0px; }
display usage: flex, according to css-tricks and MDN As follows:
.centerFlex { align-items: center; display: flex; justify-content: center; }
There are other attributes available for flex, which are further illustrated in the links mentioned above.
If you have to support older browsers that do not support css3, you might want to use a fixed width / height solution as shown in javascript or other answers.
#5 building
If you are using JQuery, you can use. position().
<div class="positionthis"></div>
CSS
.positionthis { width:100px; height:100px; position: absolute; background:blue; }
Javascript(JQuery)
$(document).ready(function () { $('.positionthis').position({ of: $(document), my: 'center center', at: 'center center', collision: 'flip flip' }); });
JSFiddle: http : //jsfiddle.net/vx9gV/
#6 building
Sorry, the best response to being late is
div { position: fixed; top: 50%; left: 50%; margin-top: -50px; margin-left: -100px; }
Margin top and margin left should be based on your div box size
#7 building
div { border-style: solid; position: fixed; width: 80%; height: 80%; left: 10%; top: 10%; }
Adjust the upper left corner of the width and height, i.e. (100% - 80%) / 2 = 10%
#8 building
I know I'm late at parties, but it's a way to center an unknown size div in an unknown size parent.
Style:
<style> .table { display: table; height: 100%; margin: 0 auto; } .table-cell { display: table-cell; vertical-align: middle; } .centered { background-color: red; } </style>
HTML:
<div class="table"> <div class="table-cell"><div class="centered">centered</div></div> </div>
Demonstration:
Look at this. Demonstration .
#9 building
In fact, there is a solution that uses css3, which can center a divs with unknown height vertically. The trick is to move the div down 50% and then use transform to restore it to the middle position. The only prerequisite is that the element to be centered must have a parent element. Example:
<div class="parent"> <div class="center-me"> Text, images, whatever suits you. </div> </div> .parent { /* height can be whatever you want, also auto if you want a child div to be responsible for the sizing */ height: 200px; } .center-me { position: relative; top: 50%; transform: translateY(-50%); /* prefixes needed for cross-browser support */ -ms-transform: translateY(-50%); -webkit-transform: translateY(-50%); }
Supported by all major browsers and IE 9 and later (don't worry about IE 8, which died with win xp this fall). Thank God.)
#10 building
from Here Another approach (bulletproof) is to use the "display: table" rule:
sign
<div class="container"> <div class="outer"> <div class="inner"> <div class="centered"> ... </div> </div> </div> </div>
CSS:
.outer { display: table; width: 100%; height: 100%; } .inner { display: table-cell; vertical-align: middle; text-align: center; } .centered { position: relative; display: inline-block; width: 50%; padding: 1em; background: orange; color: white; }
#11 building
An alternative answer is this .
<div id="container"> <div id="centered"> </div> </div>
And CSS:
#container { height: 400px; width: 400px; background-color: lightblue; text-align: center; } #container:before { height: 100%; content: ''; display: inline-block; vertical-align: middle; } #centered { width: 100px; height: 100px; background-color: blue; display: inline-block; vertical-align: middle; margin: 0 auto; }
#12 building
A simple solution with Flex Display
<div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '> <div id = 'div_you_want_centered' style = 'margin:auto;'> This will be Centered </div> </div>
See http://css-tricks.com/snippets/css/a-guide-to-flexbox/
The first div takes up the entire screen and sets display: flex for each browser. The second div (the middle DIV) takes advantage of display: flex div, where margin: auto performs well.
Note IE11 + compatibility. (IE10 with prefix).
#13 building
The simplicity of this technology is amazing:
(although this approach has its meaning, it's good if you just need to center the elements without considering the flow of the rest. Please use it carefully)
Mark:
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>
And CSS:
div { color: white; background: red; padding: 15px; position: absolute; top: 50%; left: 50%; -ms-transform: translateX(-50%) translateY(-50%); -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%); }
This also centers the element horizontally and vertically. There is no negative margin, only the power of change. Besides, we should have forgotten IE8, shouldn't we?
#14 building
When I looked at Laravel's view files, I found that they perfectly centered the text in the middle. I thought of it immediately. They do this:
<html> <head> <title>Laravel</title> <!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>--> <style> .container { margin: 0; padding: 0; width: 100%; height: 100%; display: table; } .inside { text-align: center; display: table-cell; vertical-align: middle; } </style> </head> <body> <div class="container"> <div class="inside">This text is centered</div> </div> </body>
The results look like this:
#15 building
If you are using a new browser (IE10 +),
Then you can use the transform attribute to center the div.
<div class="center-block">this is any div</div>
CSS should be:
.center-block { top:50%; left: 50%; transform: translate3d(-50%,-50%, 0); position: absolute; }
The point here is that you don't even have to specify the height and width of the div because it can handle itself.
In addition, if you want to place a div in the center of another div, just specify the location of the external div as the relative location, and then this CSS can work for your Div.
How does this work
When you specify 50% at the top left, the div will be in the bottom right quarter of the page, with the top left fixed in the center of the page. This is because the left / top attribute (when given in%) is calculated based on the height of the external div (window in your case).
But transform uses the height / width of the element to determine the translation, so the div moves to the left (50% of the width) and to the top (50% of the height), because they are negative, so align them with the center of the page.
If you have to support older browsers (and I'm sorry to include IE9), table cells are the most commonly used method.
#16 building
It is supported by the browser and has powerful translation function.
position: absolute; background-color: red; width: 70%; height: 30%; /* The translate % is relative to the size of the div and not the container*/ /* 21.42% = ( (100%-70%/2) / 0.7 ) */ /* 116.666% = ( (100%-30%/2) / 0.3 ) */ transform: translate3d( 21.42%, 116.666%, 0);
#17 building
I prefer to center the box vertically and horizontally with the following techniques:
Outer container
- There should be display: table;
Internal container
- Display: table cell;
- Should have vertical align: middle;
- Should have text align: Center;
Content box
- Display: inline block;
- The horizontal text alignment should be readjusted to for example. Text align: left; or text align: right; unless you want the text to be centered
The beauty of this technique is that you can add content to the content box without worrying about its height or width!
demonstration edition
body { margin : 0; } .outer-container { position : absolute; display: table; width: 100%; /* This could be ANY width */ height: 100%; /* This could be ANY height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .centered-content { display: inline-block; text-align: left; background: #fff; padding : 20px; border : 1px solid #000; }
<div class="outer-container"> <div class="inner-container"> <div class="centered-content"> You can put anything here! </div> </div> </div>
See also This violin !
edit
Yes, I know you can use transform: translate(-50%, -50%); more or less get the same flexibility transform: translate(-50%, -50%); or transform: translate3d(-50%,-50%, 0); the technology I proposed has better browser support. Even with the browser prefix of - webkit, - ms or - moz, transform does not provide the same browser support.
Therefore, if you are concerned about older browsers (such as IE9 and below), you should not use transform to locate.
#18 building
This is a script I wrote not long ago (it was written using the jQuery Library):
var centerIt = function (el /* (jQuery element) Element to center */) { if (!el) { return; } var moveIt = function () { var winWidth = $(window).width(); var winHeight = $(window).height(); el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px"); }; $(window).resize(moveIt); moveIt(); };
#19 building
I will use translate:
First, place the top left corner of the div in the center of the page (using position: fixed; top: 50%; left: 50%). translate then moves it up 50% of the div height to center it vertically on the page. Finally, panning also moves the div to the right 50% of its width to center it horizontally.
In fact, I think this method is better than others because it doesn't need to make any changes to the parent element.
In some cases, translate is better than translate3d because it is supported by more browsers. http://caniuse.com/#search=translate
In summary, all versions of Chrome, Firefox 3.5 +, Opera 11.5 +, Safari, IE 9 +, and Edge support this approach.
.centered { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); font-size: 20px; background-color: cyan; border: darkgreen 5px solid; padding: 5px; z-index: 100; } table { position: absolute; top: 0; left: 0; } td { position: relative; top: 0; left: 0; }
<table> <tr> <td> <div class="centered">This div<br />is centered</div> <p> Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu. </p> </td> <td> <p> Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu. </p> </td> </tr> </table>
Note, however, that this method keeps the div in one place while scrolling the page. This may be what you want, but if not, there is another way.
Now, if we try the same CSS, but the location is set to absolute, it will be in the center of the last parent with absolute location.
.centered { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); font-size: 20px; background-color: cyan; border: darkgreen 5px solid; padding: 5px; z-index: 100; } table { position: absolute; top: 0; left: 0; } td { position: relative; top: 0; left: 0; }
<table> <tr> <td> <div class="centered">This div<br />is centered</div> <p> Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu. </p> </td> <td> <p> Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu. </p> </td> </tr> </table>
#20 building
If you know the defined size of the div, you can use calc.
Real time example: https : //jsfiddle.net/o8416eq3/
Note: this only works if you hard code the width and height of the ` ` div '' in CSS.
#target { position:fixed; top: calc(50vh - 100px/2); left: calc(50vw - 200px/2); width:200px; height:100px; background-color:red; }
<div id='target'></div>
#21 building
position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%);
Explain:
Give it an absolute position (parents should have a relative position). Then, move the upper left corner to the center. Since you do not yet know the width / height, you can use the css transform to translate the position relative to the middle position. Translation (- 50%, - 50%) does reduce the x and y positions of the upper left corner by 50% of the width and height.
#22 building
This is the best code to center the div robot horizontally and vertically
div { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); }
#23 building
solution
Use only two lines of CSS to take advantage of the power of Flexbox
.parent { display: flex; } .child { margin: auto }
#24 building
Using display:grid on the parent and setting margin:auto as the first element will do the trick:
See the following code snippet:
html,body { width :100%; height:100%; margin:0; padding:0; } .container { display:grid; height:90%; background-color:blue; } .content { margin:auto; color:white; }
<div class="container"> <div class="content"> cented div here</div> </div>
#25 building
div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); /* IE 9 */ -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ }
<body> <div>Div to be aligned vertically</div> </body>
Location: absolute div in body document
The location is: absolute element; to the viewport (body tag, like fixed). The location is relative to the ancestor of the most recent location (not to the viewport (body tag), such as fixed).
However, if the absolutely positioned element has no ancestor, it uses the body of the document and moves along with the page scrolling.
Source: CSS position
#26 building
Use the following CSS properties to center elements horizontally and vertically. It's good for me.
div { position: absolute; left: 0; top: 0; right: 0; bottom: 0px; margin: auto; width: 100px; height: 100px; }
#27 building
How to use CSS Grid in 2018:
.parent{ display: grid; place-items: center center; }
Check browser support, Caniuse It is recommended that it can be used in Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check.
See the following code snippet:
.parent{ display: grid; place-items: center center; /*place-items is a shorthand for align-items and justify-items*/ height: 200px; border: 1px solid black; background: gainsboro; } .child{ background: white; }
<div class="parent"> <div class="child">Centered!</div> </div>
#28 building
To my surprise, this hasn't been mentioned yet, but the easiest way is to use the viewport size to set the height, margins (and width if necessary).
As you know, the total height of the viewport = 100vh.
Assuming that you want the height of the container to occupy 60% (60vh) of the screen, you can evenly distribute the rest (40vh) between the top and bottom margins so that the elements are automatically aligned in the center.
Setting margin left and margin right to auto ensures that the container is centered horizontally.
.container { width: 60vw; /*optional*/ height: 60vh; margin: 20vh auto; background: #333; }
<div class="container"> </div>
#29 building
Although I am too late, it is very easy and simple. The center of the page is always 50% to the left and 50% to the front. Therefore, subtract 50% from the width and height of the div, and then set the left and right borders. I want it to work everywhere-
body{ background: #EEE; } .center-div{ position: absolute; width: 200px; height: 60px; left: 50%; margin-left: -100px; top: 50%; margin-top: -30px; background: #CCC; color: #000; text-align: center; }
<div class="center-div"> <h3>This is center div</h3> </div>
#30 building
I think using flex box:
#parent { display: flex; justify-content: center; align-items: center; }
<div id="parent"> <div id="child">Hello World!</div> </div>
You will see that only three CSS properties are available to center the child elements vertically and horizontally. display: center; complete the main part by activating the flex box display, justify content: Center; center the child elements vertically, then align items: Center; horizontally. For best results, I just added a few extra styles:
#parent { display: flex; justify-content: center; align-items: center; height: 500px; width: 500px; background: yellow; } #child { width: 100px; height: 100px; background: silver; }
<div id="parent"> <div id="child">Hello World!</div> </div>
If you want to learn more about flex box, visit W3Schools , MDN or CSS-Tricks For more information.