Best way to center a
Here's a simple, clean and stable way to center divs in a container using only CSS. stackoverflow.com/a/31977476/3597276
Commented Aug 13, 2015 at 0:19 This question is marked as a duplicate of a question asked 5 years later. Oh StackOverflow. Commented Mar 20, 2021 at 18:05 margin-left: auto; margin-right: auto; Commented Nov 1, 2022 at 4:39The 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 .
5,992 36 36 gold badges 128 128 silver badges 217 217 bronze badges answered Nov 13, 2012 at 6:27 Vladimir Starkov Vladimir Starkov 19.7k 8 8 gold badges 61 61 silver badges 115 115 bronze badgesThis is awesome. I have wondered for so long how to do this. I had tried it with top: 0; and left: 0;, but it seems that the addition of bottom: 0; and right: 0; make the difference. Thank you.
Commented Jan 11, 2013 at 3:45This solution only works if your element has a fixed height. See tombul's answer for two solutions that do not change the element's natural height.
Commented Oct 8, 2013 at 21:50 Doesn't work with dynamic content – user2889419 Commented Sep 6, 2014 at 23:04 @FlashThunder you suggest tables for non-table data, aren't you? Commented Jan 10, 2015 at 3:17 Excellent! I did not even know bottom: and right: existed in css. Commented Jun 14, 2017 at 10:29Even 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:
.centerPseudo < display:inline-block; text-align:center; >.centerPseudo::before
The usage of display: flex, according to css-tricks and MDN is as follows:
.centerFlex
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.
answered Sep 4, 2013 at 15:43 1,817 1 1 gold badge 13 13 silver badges 11 11 bronze badgesAll browsers from 2012–2013 upwards support flex boxes. From today’s standpoint it should be safe enough to use it for new applications under most circumstances. The only situation I can think of where the older model should be preferred are business customers who rely on older infrastructure and can’t upgrade.
Commented Aug 23, 2015 at 15:56Simplicity of this technique is stunning:
(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. Use with care)
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.
This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?
21.7k 10 10 gold badges 90 90 silver badges 78 78 bronze badges answered Jan 16, 2015 at 16:03 3,788 3 3 gold badges 33 33 silver badges 37 37 bronze badgesYes, I used a lot this method. but, problem come if element is much higher then screen height (where height is unknown) . top of centered element would be cut. Even if element is putted in parent element where overflow is set to auto or scroll . Same problem using flex . Unfortunately, like last resort I use table to override this problem. Only when centered element will be much, much higher (dynamically populated).
Commented Oct 27, 2015 at 6:59 I had to set position to relative, probably because my div floats right. Commented Feb 28, 2016 at 3:22Nelek - if parent element has fixed width and height you can add max-width:100% and max-height:100% to the image and prevent it from expanding the parent
Commented Jan 9, 2017 at 0:16Please check it in box model. its not coming on center. its showing as center but its exact pixel values are not there.
Commented Sep 2, 2020 at 6:52I would use translate :
First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50% ). Then, translate moves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.
I actually think that this method is better than many of the others, since it does not require any changes on the parent element.
translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d
To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.
.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
This div
is centered 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.
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.
Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.
Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.
.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
This div
is centered 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.
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.