13 ms·
The complete guide to centering a div
- JazCE 13y agoShame that demo's take you out of the site.
- apu 13y agoThe critical piece I'm always missing is how to center a div vertically if you don't know its height?
- igvadaimon 13y agoWell, I'd use display:table-cell with vertical-align:middle.
- platypii 13y agoDoesn't work without the parent having a defined height.
- IvarRafn 13y agoI found this a few days ago, I haven't tried it yet but it looks promising. http://snippetrepo.com/snippets/vertical-align-anything-with-3-lines-of-css http://snippetrepo.com/snippets/vertical-align-anything-with...
- cheapsteak 13y agoDid he make a typo? http://codepen.io/cheapsteak/pen/axJit http://codepen.io/cheapsteak/pen/axJit Doesn't work, unless you change `position: relative` to `position: absolute`
- mbell 13y agoHeres's a trick using pseudo elements : http://codepen.io/anon/pen/pIFna http://codepen.io/anon/pen/pIFna
- maj0rhn 13y agoThis is a pointless post. Use the TABLE tag. Yes, it will violate the purity of CSS, but you can trust it, and it will make your day better because it will free you angst and from extensive cross-browser testing. Simple is better than complex. Straightforward is better than arcane.
- _mtr 13y agoUsing display: table-cell on a div is a more semantic approach than using <table>.
- deleted 13y ago[deleted]
- peter_l_downs 13y agoAs igvadaimon wrote below, there's no need for a <table> tag. Instead of: <table> <tr> <td> my div </td> </tr> </table> you can do <div style="display: table;"> <div style="display: table-cell; vertical-align: middle;"> my div </div> </div> The inline styling is just for illustrative purposes, of course.
- maj0rhn 13y agoI'll admit that the table-cell approach is nice -- thank you. But how curious that the article, which purports to be an in-depth examination, doesn't mention it. And how curious that the table-cell approach has not turned up in the numerous times I've gone looking on-line for a robust, pure CSS solution. I've long harbored suspicions that many CSS gurus are too quick to adopt complex solutions.
- michaelfdeberry 13y agoI don't know the current state of browser's but the is likely because, at least at one time, the display type of table wasn't widely supported. On the other hand support for centering vertically with auto isn't/wasn't widely supported either.
- joshfraser 13y ago<center><div>I'm centered!</div></center>
- _mtr 13y agoDRY, though, right? Changing one set of CSS rules is better than hunting down 20 <center> elements when requirements change. Not to mention <center> is deprecated.
- dangrossman 13y agoWhen requirements change — center { text-align: left }
- userbinator 13y agoA simple search-and-replace is enough to get all the <center> elements... and chances are when the requirements change, that's the least of the structural changes you'll have to make. IMHO all the CSS purists do is overcomplicate things.
- peter_l_downs 13y agoThat works great vertically! </sarcasm> Did you even read the article?
- dkersten 13y agoTime to introduce a new tag into the standard! <vertical-center>Hello!</vertical-center>
- joshfraser 13y agoRelax, I'm not recommending anyone actually do it that way. I'm just old and found it humorous that something as simple as centering a div requires an entire article.
- deleted 13y ago[deleted]
- bliker 13y agoI was wondering why the demo is not working for me. it really took me a while to realize that it is actually a button.
- tiziano88 13y agodamn, I thought that box was supposed to show the alignment of the div itself too, and I couldn't figure out why it looked always the same
- 10feet 13y agoObviously you can't show off css in the same browser window as your text, that would be insane. No, you have to load up a completely different website, that makes much more sense.
- SteveP1961 13y agoCodePen shows live code that can be edited and played around with. It does make sense.
- 10feet 13y agoNo, it does not. It is good to be able to play around with the code, but to require someone to see the code working it is overkill.
- SteveP1961 13y agoOkay, good point. :-) I've changed it and hopefully it's more obvious.
- hawkharris 13y agoWhat about cases in which developer wants to vertically center a div, but he or she doesn't want to specify a height property?
- Mandatum 13y agoThen unfortunately you have to calculate it with JS if it varies. Vertically centering divs has always been a gigantic pain-in-the-ass. If anyone has a better idea for doing this without JS, please let me know. Once CSS implements variable-based elements (ie #div.height) then we'll have a lot more control.
- markdown 13y ago> If anyone has a better idea for doing this without JS, please let me know. Flexbox, with optional fallback to JS for IE 8 and 9. That said, vertical centering is almost always a nice-to-have rather than a must-have so personally I wouldn't even use a fallback. http://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ http://philipwalton.github.io/solved-by-flexbox/demos/vertic... http://caniuse.com/flexbox http://caniuse.com/flexbox
- deleted 13y ago[deleted]
- lobster_johnson 13y agoAs mentioned elsewhere: "display: table-cell" with "vertical-align: middle".
- lobster_johnson 13y ago"display: table-cell" with "vertical-align: middle" works.
- halisaurus 13y agoThat this is missing is surprising. This method is the most compatible across browsers and only real drawback is the additional markup.
- shawnz 13y ago> Centering a div Within a div, Horizontally and Vertically The code in this section is incorrect. "margin: auto" does nothing in the vertical direction. If you set the height of the outer div to something more than 160 px, you will see that the inner div is not centered.
- jessedhillon 13y agoCame here to say the same thing. Not sure the rest of the article is worth reading if the author doesn't know CSS well enough that a) they don't know a priori that this is wrong, and b) manages to convince themselves it's true using Codepen Here's the Codepen that shows it with a larger outer div, http://codepen.io/jessedhillon/pen/CDqEe http://codepen.io/jessedhillon/pen/CDqEe
- SteveP1961 13y agoNo, it doesn't work with a fixed height. I didn't claim it did, of course. In a responsive world fixed heights in a container are somewhat irrelevant, but I'll amend the article.
- jessedhillon 13y agoWhat? It doesn't work at all -- without a fixed height, the height of #outer would be determined by summing the heights of its statically/relatively positioned children. If there were multiple children of #outer, #inner would still not be centered vertically. This only works for some trivial definition of vertical centering, when what you really mean is that a single block child will occupy the vertical center position of its block parent, provided the parent's height is not specified. Which is the most obvious of statements in CSS.
- SteveP1961 13y agoIt works in a container with no fixed height. Perhaps it doesn't work for your particular requirements, but it does work.
- lpolovets 13y agoI don't know anything about the history of CSS's design, but I'm perpetually amazed that positioning (and specifically centering) requires so much CSS magic. I would think CSS positioning would be a one-liner, but instead it's a collection of context-dependent, browser-dependent recipes. I wonder if there's a good reason for the madness, or if it's just poor design. (FWIW, I'm a backend engineer and have only dabbled with front-end code.)
- masklinn 13y ago> I wonder if there's a good reason for the madness Well the reason is that CSS originally wasn't intended for layout…. But since there was no other tool for layout, once the web design community decided to remove tables from layout it got drafted despite being severely insufficient. Layout modules have just started being developed, fought upon and implemented in the last few years. Here's how vertical centering looks like when using flexbox (http://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ http://philipwalton.github.io/solved-by-flexbox/demos/vertic...): .parent { display: flex; align-items: center; justify-content: center; } .centered { max-width: 50%; } (note: this ignores prefixing, specs differences and browser-specific issues, here's the component https://github.com/philipwalton/solved-by-flexbox/blob/master/_sass/components/_aligner.scss https://github.com/philipwalton/solved-by-flexbox/blob/maste... which is itself expanded to suit browsers)
- hamburglar 13y agoThe sad thing is that I'm going to bookmark this.
- cema 13y agoWell, I have bookmarked it both for the article contents and for the discussion. As is often the case.
- Tloewald 13y agoThe thing that boggles my mind is that we're over ten years and three major versions in and we can't center stuff reliably or conveniently, images won't scale up to fit (only down...), multi-column text is barely implemented and Google is ripping it out, the box model is borked by default, it's non-trivial to determine the layering of UI elements, and so on. It's amazing that we get solutions for things that no-one really needs (animated 3d transitions...) while bread and butter stuff still requires rocket science. Back in 2005 I used to joke that 90% of the world's Javascript was just doing button rollovers (probably a conservative estimate) — well, CSS eventually fixed that, kind of — now Javascript is mostly doing similarly idiotic stuff like handling resizing, making things that aren't lists impersonate lists because multi-selects are borked, centering stuff, and trying to reliably hook up event handlers. All of which were solved problems before the web was born.
- level09 13y agonice list, would be nicer to have a more detailed definition of "modern browsers" , like browser types/versions that support each method.
- SteveP1961 13y agoNoted. Thanks.
- lisper 13y agoI wrote this five years ago. I'm somewhat dismayed at how relevant it still is today: http://www.flownet.com/ron/css-rant.html http://www.flownet.com/ron/css-rant.html
- leephillips 13y agoThat article, and especially the second followup, are brilliant. Well argued, sharply written.
- lisper 13y agoThank you!
- mcot2 13y agoI've been using Flexbox for a while now. Unless you need to support older IE than it is quite usable. The one problem is the older syntax for IE10 but it is fixed in IE11 and going forward.
- sideproject 13y agoanyone miss <center> tag? :)
- sfaruque 13y agoI'm curious, why did they remove the <center> tag? What was wrong with it?
- crazygringo 13y agoWhenever anybody says that CSS is easy, or "of course you can do that with CSS", or even hints that CSS is somehow well-designed... ...the only thing I really need to say, is that every couple months, on Hacker News, where a lot of really smart people hang out, a new top-voted story comes up about how to center a div. With tons of comments and discussion too. And it's not even a joke. What more is there to say?
- adwf 13y agoNext week: The complete guide to sticky footers! It's unbelievable just how annoying CSS can be for seemingly simple things.
- sopooneo 13y agoI may be using words incorrectly, and I'm not positive you can even make the distinction, and I am happy to stand corrected, but it always seemed to me that CSS was fine for style, but terrible for layout. So I think I'm agreeing with you.
- jebblue 13y agoRight, to me plain HTML tables are great for overall master page layout yet it seems everything I've read and the few web geniuses I've met will deride using them over CSS.
- msie 13y agoIs there a framework that allows one to avoid most of CSS and just use js?
- sehr 13y agoEven if there was, if something went wrong you'd just have more shit to sift through.
- mrmartineau 13y agoFor an in-depth look at all the different options for centering an element, have a look at Stephen Shaw's research on Codepen: http://codepen.io/shshaw/full/gEiDt http://codepen.io/shshaw/full/gEiDt
- addedlovely 13y agoA few additions. If you know the width and height of the element, centering horizontally & vertically can be achieved with one <div> like so: .center-div { height:100px; width: 100px; position:absolute; top:50%; left:50%; margin: -50px 0 0 -50px; } This can be modified for the 'centering at the bottom of the page' example, but with more efficient code. More challenging is centering the unknown: http://css-tricks.com/centering-in-the-unknown/ http://css-tricks.com/centering-in-the-unknown/
- DigitalSea 13y agoMy utmost favourite technique for centering unknown width and height DIV's/elements perfectly center in the page is using 2dtransforms. I've created a Codepen here that shows off the technique, it's simple and well supported IE9+: http://codepen.io/Figurated/pen/zcypx http://codepen.io/Figurated/pen/zcypx — if you don't need to support IE8 any more, it's a perfect solution.
- hesslau_ 13y agoMy favourite technique: position absolute and top: 0 bottom: 0 left: 0 right: 0 also doesn't require a fixed width http://codepen.io/anon/pen/vsliJ http://codepen.io/anon/pen/vsliJ
- grannyg00se 13y agoThat's great! And it seems to have pretty good browser support.
- olivier1664 13y agoYour technique is less good (on IE11) when you resize the width of the browser. The text finish outside the div, while DigitalSea's solution works well.
- runn1ng 13y ago.... <center> will not work?
- _mtr 13y ago> This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ce...
- Zarel 13y agoIt also won't work because <center> controls text alignment and will have no effect on the alignment of a div (it will center its contents, though) (also this isn't entirely true, centering text will also center divs in IE6 and earlier).
- EGreg 13y agoAfter IE6, we can just center a div using inline-block, can't we? The outer element can have display: table-cell and the inner element would have vertical-align: middle and display: inline-block.
- boyaka 13y agoI've been working on this form with php [1]. Only positioning I've tried so far is using tables. Focusing on functionality for now, figure I can just wait til it works to make it look pretty. Haven't really worked to understand CSS since I was in middle school in the late 90s. [1] http://i.imgur.com/eRbSdbT.png http://i.imgur.com/eRbSdbT.png
- clhodapp 13y agoThe Web Styling Challenge: you and another person are going to make a web site. You are doing the HTML, while the other person does the CSS (you can discuss it and swap jobs if you want). You can talk as much as you want ahead of time, but the only record you can keep is a table that maps CSS selectors to a description of what you'll be using them for. You are then split up and do your individual tasks. When you're finished, you will be judged on how broken the results of combining your pages with the other person's stylesheets are. I think just imagining how this game would go makes it pretty clear that CSS is lousy at separating the concerns of style and layout.
- TheZenPsycho 13y agoOf course, CSS was a compromise between old guard semantic "purists" (who envisioned an HTML document as being pure text with structural meaning semantically applied to the content via tags, with the browser in full control of presentation) and designers, who wanted control over look and layout (the fools!). And so, CSS was created, and designers could have their silly colours and fonts. Any layout or typographic abilities were added as a neglected and poorly considered afterthought. Designers being what they are, worked out systems like tables, and the hacks in the link to get what they want out of CSS anyway. (but why would you want to centre anything? that's stupid! the original designers of CSS grumble) meanwhile, far superior systems, such as "Constraints Based CSS" were proposed, and ultimately rejected because it's stupid and irresponsible to want to control the layout of a webpage! Now it's 2014 and we have flex box as a patch over. Constraints based css would have been much better, and that's what you get in Cocoa Auto-layout now, but oh well. let's copy java and flash. what difference does it make? http://www.cs.washington.edu/research/constraints/web/ccss-uwtr.pdf http://www.cs.washington.edu/research/constraints/web/ccss-u...
- null_ptr 13y agoIs it me or is the content of this page annoyingly off-centered?
- DavidSJ 13y agoFrom six years ago, during which it would seem CSS has gotten no better: http://beradrian.files.wordpress.com/2008/01/breakdown.png http://beradrian.files.wordpress.com/2008/01/breakdown.png
- greatsuccess 13y agoThe fact that centering a div requires a complete guide is tragicomically sad and a condemnation of our industry.
- tkirchner 13y agoThere is really not much more to say... ...maybe that the reason for all of this is that the CSS API (box model ..., box properties ...) is too complex and as a result browser implementations tend to f* it up easily.
- tkirchner 13y agoThere is really not much more to say... ...maybe that the reason for all of this is that the CSS API (box model ..., box properties ...) is too complex and as a result browser implementations tend to f* it up easily.
- STRML 13y agoThis is my favorite vertical centering method [1] and combined with the table/table-cell method, it allows me to avoid using JS for layout about 95% of the time. It's not very well-known and even though I've used CSS for well over a decade, I have no idea why it works. The real trick is realizing that `margin:auto` actually does do something, so long as you set a fixed width/height and position: absolute with dimensions set to 0. But for the life of me, I don't understand why that happens to trick the box model into working properly. But this technique is fantastic and really helps out when table/table-cell interacts badly with your styles, or you need to support older browsers. I would be very happy if someone in the know could explain why this technique works. [1] http://codepen.io/anon/pen/whHIL http://codepen.io/anon/pen/whHIL
- angersock 13y agoDespite a wonderful article, I cannot help but notice that it is 2014 and we still need multiple ways of centering a div. :(
- tagliala 13y ago...and the one that really works (variable height and width) uses `display: table` :(
- kyberias 13y agoIs this article intentionally ironic with a column of text that isn't centered as the header is?
- potch 13y agoThis article is not actually correct. There are really 2 or three techniques for centering a block level element. The post repeats these techniques for multiple scenarios, and is wrong about the first vertical centering technique.
- CmonDev 13y agoAll the problems with HTML and CSS in one title. All hail the "modern GUI development"!
- whalesalad 13y agoThe irony here is that the content of this post is not centered.
- rcruzeiro 13y agoOne day someone will have to come up with a convincing explanation on why the hell is margin: auto; unable to vertically center an element if the outer element has a defined height.
- trajektorijus 13y agoBest centering (vert. and hor.) solution ever: .outer { position: relative; } .inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } <div class="outer"> <div class="inner"></div> </div> This way you don't need to know the width or height of inner element...
- burgerguyg 13y agoMaybe I'm thick. The article is dated February 2014, it says flexbox "currently lacks browser support, mainly in IE (version 10 has partial support and full support won't arrive until version 11). Chrome, Safari and Firefox have support but with browser vendor prefixes." IE11 came out in preview in June 2013, released officially in November 2013, and at least IE and Mozilla are currently supporting it unprefixed (though Mozilla's multi-line flexbox fails last time I checked). This article is over 3 months out of date, if not more, but being presented as new and current.