18 ms·
How to Center in CSS
- hachre 12y agoGreat!!!
- binwiederhier 12y agoAwesome!
- michaelbuddy 12y agoIf OP is the creator of the site, the width and height boxes are really small on firefox desktop. I'm thinking at least show 3 characters wide, even four would be smart.
- yefim 12y agoFinally! I can't believe this is still such a big problem in CSS today.
- picardo 12y agoThis might need some updating. I did a quick run through and it recommended me to use a table-cell for vertical centering. You might be able to do that more easily with flexbox.
- acdha 12y agoDepends on what you need for browser support – flexbox is supported in fewer browser versions and requires using multiple rules because the spec changed significantly before finalizing: http://caniuse.com/#feat=css-table http://caniuse.com/#feat=css-table http://caniuse.com/#feat=flexbox http://caniuse.com/#feat=flexbox
- sondr3 12y agoWhich is why you use something like AutoPrefixer to automagically generate the needed browser prefixes and such, makes it a whole lot easier.
- actionscripted 12y agoWhich still doesn't cover older browsers just prefixes things appropriately for those that support it.
- sondr3 12y agoFair enough, but for my uses 92% browser support is more than enough, it's the same as ems/rems for example.
- kagamine 12y agoBut for older browsers you can use the old specification too. This means including the old specification before the new one in the CSS block; that will provide a warning in the web-inspector. Then you will need a hack for <=IE8, but I have had this working on a site since autumn 2013 (not a public site and I therefore knew what browser versions had access). It is doable and it provides a flexible layout. here is a sample (btw, it's so long ago now, I included modernizer.js and slectivizr.js but I have no idea if they were anything to do with this >_< and why I keep referencing "flexie" I have no idea, the script, if it even was a script isn't included on the page.... SO professional, such memory... ): #box_content { /* 1st draft flexbox required for IE8 layout using 'flexie' */ display: -moz-box; display:-webkit-box; display: -ms-box; display: box; -webkit-box-orient:horizontal; -moz-box-orient:horizontal; -ms-box-orient:horizontal; box-orient: horizontal; -webkit-box-align:center; -moz-box-align:center; -ms-box-align:center; box-align:center; -webkit-box-direction:normal; -moz-box-direction:normal; -ms-box-direction:normal; box-direction:normal; -webkit-box-pack:center; -moz-box-pack:center; -ms-box-pack:center; box-pack:center; /* 2013 flexbox! for FF3+, Safari3.2+, Chrome5+ */ display: flex; display: -moz-flexbox; display: -webkit-flexbox; display: -ms-flexbox; flex-flow: row wrap; justify-content: space-around; padding-bottom: 1.5em; } .phonebox, .addressbox, .qrbox, .emailbox { max-width: 250px; min-width: 200px; height: 165px; display: block; border-radius: 20px; color: #4d4d4d; box-shadow: 2px 2px 9px #333; border: 1px solid #A2E86C; margin-top: 0.5em;/* req. for small screens */ /* More flexbox for older browsers (flexie.js)*/ -webkit-box-flex:0; -moz-box-flex:0; box-flex:0; -webkit-box-ordinal-group:1; -moz-box-ordinal-group:1; -ms-box-ordinal-group:1; box-ordinal-group:1; }
- tomasien 12y agoI remember when I was first learning CSS and I found out this wasn't easy. I thought "oh my god, this learning to code stuff is gonna be HARD!" A few years later and I don't think anything but the occasional third party api with undocumented behavior has been nearly as hard.
- lucaspottersky 12y agooh man, that's a mad world we live in. look at that. it's just sad to think that a browser can do so much stuff, yet it's unable to provide a good layout system.
- davesque 12y agoIt's good at what it was originally designed for: flowable text documents. And, honestly, it's come a long way since its early days. Used to be much worse.
- pcwalton 12y agoThis site doesn't seem to be suggesting absolute centering [1] when it would be the easiest way to center things. "margin: auto" seems to be the way that the designers of CSS 2.1 intended to center things. 90% of the time, absolute centering is the easiest way to center in CSS; you should prefer it when possible. [1]: http://codepen.io/shshaw/full/gEiDt http://codepen.io/shshaw/full/gEiDt
- ChrisGaudreau 12y agoWould this technique work to center, say, an <img> tag with undeclared dimensions inside of a div? Or do you have to jump through hoops?
- pcwalton 12y agoNo, if you don't have a defined height you will need to either use "display: table", the table-cell technique, or flexbox. When I told the site that I had a defined height, however, it still suggested the table-cell trick, which was not the optimal solution because of the extra markup required. In my experience, most of the time when I do want to center something vertically, I have a defined height (which can be a percentage!), so absolute centering is the solution of choice.
- padolsey 12y agoWith no defined height you can still use the `translate(-50%, -50%)` hack, right? I'm kinda surprised it hasn't been mentioned in this thread at all; I use it all the time. http://codepen.io/padolsey/pen/NqKzVG http://codepen.io/padolsey/pen/NqKzVG
- undefined0 12y agoAn image can be vertically aligned with vertical-align: middle; and centered with text-align: center; Firefox uses pcwaltons method for images (resource://gre/res/TopLevelImageDocument.css). Do you want the image to be in the center/vertical of the div (with the div having a specified height)? If so, then pcwaltons method should work, as long as you have position:relative; on the div.
- mhink 12y agoDoesn't Flexbox pretty much solve this problem? I mean, if you need to maintain backwards compatibility this might be reasonable, but "justify-content: center" and "align-items: center" seem to work unreasonably well for this exact purpose.
- nkozyra 12y agoFlexbox solves this problem but it's still a bit unwieldy and verbose.
- sondr3 12y agoVerbose? Compared to the other solutions it's a godsend, just use the CSS-tricks guide for it and you'll have nearly zero problems. I absolutely love it and pretty much refuse to use anything else for layout in CSS now.
- Cub3 12y agoJust remember IE10 only supports the 2010 flexbox spec (you can't inline-flex, need -ms-prefix etc.)
- nkozyra 12y agoCompared to the rest of the CSS spec, I'd say so. It certainly solves the problem much better, though.
- drcode 12y agoIMHO constraint systems like GSS (http://gridstylesheets.org/ http://gridstylesheets.org/) handle centering in a much cleaner way. Pity that approach hasn't gotten any traction (though some people smarter than me say it's a bad idea, so who knows what the right answer is...)
- woah 12y agoI much prefer the deterministic flex box to the mysterious auto layout, even if you might have to use a container div here and there. I think constraint solving is a fascinating idea, but it always seems to end up involving me setting magic priority numbers with little understanding as to why.
- justindocanto 12y agoThe table-cell solution for vertically centering text is incorrect. You need to put that display:table-cell div inside a display:table div. It requires the parent in order to work properly. Example: <div class="item"><div><p>Your text here</p></div></div> .item {display:table;} .item > div {display:table-cell;vertical-align:middle;} I use this method on justindocanto.com to vertically center an unknown amount of text/elements inside a div that changes its size based on the size of the image that's inside it. Really nice technique when used correctly.
- scotty79 12y agoYes. This page gives wrong solutions for unknown size of centered block but known sizes of container.
- chubs 12y agoWow CSS is unfriendly, you really realise how poor it is once you learn other layout systems (android's XML and iOS auto layout, etc). Wish there was another standard that could co-exist side by side on the web, something simple enough to be implemented reliably by the browser vendors.
- pcwalton 12y ago> Wish there was another standard that could co-exist side by side on the web, something simple enough to be implemented reliably by the browser vendors. That standard exists. It's called flexbox. It was designed to solve exactly this problem (among many others), and does. That said, as I never tire of mentioning, vertical centering was a part of the design of CSS 2.1. The technique is called "absolute centering". See CSS 2.1 10.6.4 [1]: "If both 'margin-top' and 'margin-bottom' are 'auto', solve the equation under the extra constraint that the two margins get equal values." [1]: http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-height http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-hei...
- angersock 12y agoBut then what happened to it? wtf? do...do they know...how many manhours could've been saved...?
- pcwalton 12y agoYeah, everyone did a really bad job of evangelizing absolute centering back in the day, leading to lots of angry Web developers and awful hacks like the inline-block/vertical-align trick. It should have been the first example given for "position: absolute"…
- AustinG08 12y agoNothing happened to it. It gets used by front-end developers every single day. I personally can't follow the CSS complaints. It is easier to learn than any other front-end dev language in one's toolkit.
- 12y ago
- crimsonalucard 12y agoThis is why css is fundamentally broken. Centering should be a feature in itself. I shouldn't be manipulating other attributes to achieve centering.
- pcwalton 12y agoIt is a feature of CSS 2.1. See my reply to chubs above. CSS 2.1 10.6.4 requires that "margin: auto" on both sides of an absolutely-positioned element mean "vertically center it".
- Retra 12y agoThat's really counterintuitive; the vertical center isn't an absolute position.
- pcwalton 12y agoYou need absolute positioning because margins in the normal flow are special in that they're subject to margin collapse, and trying to specify some sort of special interaction between margin collapse and "margin: auto" would be too complex. Absolute positioning is also nice because it has a well-defined notion of a containing block, which allows CSS 2.1 to easily define "what I'm vertically centering relative to". The way absolute centering vertical alignment works in CSS makes sense once you understand containing blocks: you specify "position: absolute" to disable margin collapse and establish a containing block, you specify the offsets from the edges of the containing block that you want, and then you invoke the vertical-centering feature in CSS by saying "margin: auto".
- Retra 12y agoIf I wanted to do those things, I should write "margin-collapse: disabled" and "vertical-align: center". Making your abstractions leaky on purpose doesn't mean you're justified in doing it. I don't understand CSS all that well, but I do understand basic layout concepts and my specific intent, and it isn't very productive to have to wait around for people like you to write books and answer stack overflow questions just so I can use CSS to do what it was designed to do. If I write "margin: auto" on an absolutely positioned element, I would expect it to do nothing, since those are just contradictory demands. I wouldn't expect it to do something completely unrelated like vertical centering.
- mambodog 12y agoThis should also have an option for 'what browsers do you need to support' and just provide flexbox output instead if you don't need to support legacy IE.
- explosion 12y agoI like that tool very much, but it would be nice to see the generated CSS styles displayed separately from the HTML. By this, I mean generating the following individually: 1) the HTML with a class applied to a sample element to be centered 2) the separate CSS for that particular class selector This is just a little nitpick based on my preference for avoiding inline styles; overall, nice work!
- DiThi 12y agoAs others said, flexbox is a complete replacement for all layour hacks in CSS. This site helped me understand flexbox: http://flexboxin5.com/ http://flexboxin5.com/ Browser support: http://caniuse.com/#feat=flexbox http://caniuse.com/#feat=flexbox
- jimmcslim 12y agoI've understood that Flexbox is what you should use for 'small layout' (controls, etc) but ultimately we should be using the new CSS grid module for 'large layout' (pages). http://dev.w3.org/csswg/css-grid/ http://dev.w3.org/csswg/css-grid/ Of course, it might be a while until there is broad browser support! http://caniuse.com/#feat=css-grid http://caniuse.com/#feat=css-grid
- runarberg 12y agoI'd think you should use flexbox for what it's good at --calculating and distributing the available space on it's children-- and grid for what it's good at --enforcing strict and precise layout outlines--.
- lnanek2 12y agoHmm, that http://flexboxin5.com/ http://flexboxin5.com/ site didn't work in Chrome at all. Claimed it was going to resize when I pressed resize it early on and did nothing.
- phamilton 12y agoSame. Debug console: main.js:769 made it this far main.js:1182 nope, not happenin today sir.
- davesque 12y agoHmm...I didn't have any problems with it in Chrome.
- SquareWheel 12y ago
- jrm2k6 12y agoFlexbox++
- jessekiddd 12y agoI was struggling with this yesterday
- bhousel 12y agoI can't think of a technology that has both saved and wasted more of my time than CSS.
- imakesnowflakes 12y agoGit
- bifurcations 12y agoWould have been great to have this when I was first learning CSS. Problems like this one are what made me so reluctant to touch frontend for a long time.
- lisper 12y agoThe mere fact that a site like this can exist and not be a joke is proof that CSS is still badly broken. I should be able to center things by writing: foo { align: center; valign: center; }
- cyphunk 12y agoEvery 4 years: "lets check if latest css can center dynamic sized things without a bunch of #container_of_container cruft". Just stick with: <table height=100% width=100%><td valign=center align=center> And what the hell does "margin: auto" mean? I'd like to hear some print designers using that in normal conversation. "oh and also i'd like these margin's auto'ed". At this rate the table tag is going live longer than the copyright on mickey mouse.
- psychometry 12y agoNo, use divs and table-cell display values if you want to have non-tabular data displayed like a table.
- cyphunk 12y agoIndeed I have non-TABular data and yet I should use TABle-cell? I'll just stick with the actual <table> then. cleaner. But the real problem is "use divs". plural. so already breaking the #container_of_container cruft rule. I'd rather write some javascript with overly nested callbacks and leave the html clean. thanks.
- carsongross 12y agoI am reminded of one of my favorite tweets of all time: “The easiest way to vertically center something in CSS is to close your laptop and go to the bar.” - @jakeboxer https://twitter.com/thedaniel/status/414123893830336513 https://twitter.com/thedaniel/status/414123893830336513
- peterjmag 12y agoThis one cracked me up too: “How to choose between rem and em” 1. question css 2. question your life 3. throw away laptop 4. scamper into forest https://twitter.com/iamdevloper/status/587651586350002176 https://twitter.com/iamdevloper/status/587651586350002176
- aps-sids 12y agoThis site should give HTML and CSS separately, rather than giving inline CSS.
- kijin 12y agoMaybe it's just me, but I find it much easier to understand exactly how a proposed solution works when it uses inline CSS. If the HTML and CSS appear separately, I have to look back and forth a lot to make sense of the whole. Of course, when I actually implement it in my design, I prefer to separate my CSS from my HTML. I wish the solution was presented in both flavors, side by side.
- polygonplanet 12y agoResult display is too passive. But, radio buttons are so good design.
- SimeVidas 12y agoAll the people who are still perplexed by this, have to admit that they haven’t heard of or tried flexbox. It works beautifully (in conjunction with Autoprefixer).
- mark_up 12y ago> (in conjunction with Autoprefixer). Then not beautifully at all. It would be beautiful if it worked on IE8+ without the use of any 3rd party plugins.
- stormbrew 12y agoHere's the thing: Most of us who are perplexed are actually perplexed because is was something you used to be able to do trivially and then a new standard came along and made it unreasonably hard for about 15 years. An eternity in software development. Entire generations of paradigms have come and gone in the time it's taken for CSS to fill this gap. That will never stop being perplexing, no matter how many new models they throw on top to try to fix it.
- intruder 12y agoHeard of flexbox, it's nice but here's one thing I haven't been able to do with it: Center a bunch boxes in a row and have overflowing boxes show up on the next row to the left or right. Doesn't work, it will center the next row as well. I haven't found a non JS solution to this yet.
- seekingcharlie 12y agoNot sure if I know exactly what you mean, but can you use :nth-child for the nth box that shouldn't be centered?
- DiNovi 12y agonot sure excalty what you're descibing, but shouldnt flex-wrap work to fix this?
- cyphunk 12y agoflexbox will be nice. once widely supported. <div style="display:flex; align-items:center; justify-content:center; width:100%; height:100%">dynamic both v and h aligned center</div>
- neya 12y agoWow, this IS a huge pain solver. I can't simply recall how many nights I've been spending trying to fix the centering in CSS during my early days as a frontend dev. Thank you,bookmarked!
- andrewliebchen 12y agoAll mediums have constraints. Perhaps our designs should be better a working within those constraints. Obviously, vertically centering in all situations is something CSS doesn't do so well in some situations and just fine in others. Know the situations in which it doesn't work and design another solution.
- MichaelCrawford 12y agoa bunch of non-breaking spaces on other side?
- sanbor 12y agoAnother way to center flexible boxes is to use css transforms http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/ http://zerosixthree.se/vertical-align-anything-with-just-3-l... CSS transforms have pretty good browser support http://caniuse.com/#feat=transforms2d http://caniuse.com/#feat=transforms2d
- lucb1e 12y agoThis looks really useful. In case the author reads this, one addition it could use is explaining why the given css works. And, like someone else already mentioned, indicate browser support. I haven't used this display:table-cell before and I wonder about its support. A small thing to lookup, sure, but it would be nice built-in. Or selecting which browsers you need to support and using flexbox when possible.
- chad_strategic 12y agoDisrupt CSS
- mmphosis 12y agoeasy: <center>Disrupt</center>
- damian2000 12y ago+1 more reason to avoid web development whenever possible. ;-)
- afarrell 12y agoThis is the sort of thing that makes me conclude that the right way to teach oneself html+CSS is to read about the basics and then just find 100 increasingly-difficult layouts to implement and grind through them.
- jan-hocevar 12y agoScroll down after generating code, but other than that, great!
- devsquid 12y agoFlex plox
- devsquid 12y agoFlex plox
- superasn 12y agoI really miss the HBox and VBox of Adobe Flex. They made aligning content so damn easy (and it was responsive, no media queries either) <HBox height="100%" width="100%" horizontalAlign="center" verticalAlign="middle"> <VBox>Col 1</VBox> <VBox>Col 2</VBox> <VBox>Col 3</VBox> </HBox>
- hawleyal 12y agoEw, Adobe Flex
- riquito 12y agoTime to learn flexbox http://flexboxin5.com/ http://flexboxin5.com/
- sukumargv 12y agoGod Bless this guy!
- eddd 12y agoThis actually proves that CSS is broken. I just want to say: 'put this content in the middle' nothing else. That is the reason why I am trying to avoid doing frontend whenever possible - it just sucks. Luckily Elm(http://elm-lang.org/Learn.elm http://elm-lang.org/Learn.elm) tries to solve that problem and i hope it will get some traction very soon.
- rivo 12y agoUnfortunately, this page does not give a solution to a long-standing centering problem I've had: Given a single DIV of unknown width and height, how do I center it in the middle of the screen (floating, i.e. fixed)? Note the "single DIV" so no wrapping in additional container DIVs! The only approximation I could find was this: .mydiv { position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); } This, however, looks horrible on most browsers as they either use hardware acceleration (resulting in blurry output) or they drop pixels (e.g. single-pixel lines) falling between the grid.
- kowdermeister 12y agoFlexbox does it for you. http://codepen.io/kowdermeister/pen/mJbGdr http://codepen.io/kowdermeister/pen/mJbGdr
- rivo 12y agoThis also relies on a container DIV (".overlay"). So Flexbox doesn't help here.
- kowdermeister 12y agoWhy is that a problem? In real life you always have a container div.
- talmand 12y agoWhat exactly is your centered div centering to if there's no container div? The .overlay div is the container, the .dialog div is centering itself as defined by constraints of .overlay. I'm failing to understand your expectations.
- rivo 12y agoLet's say this is a modal dialog which is supposed to appear in the center of the screen, fixed (but the size is unknown and may scale with its contents). With any of the existing solutions, the HTML code for the dialog will always be <div><div>...</div></div>, i.e. unnecessary DIVs due to the limitations of CSS. Since it is supposed to float on top of everything else, it does not matter what its container is. May as well be the <body> tag but applying flexbox to that tag is likely not an option.
- sengork 12y agoNote to self: the title of this article does not refer to aim-bots in Counter Strike Source...
- raverbashing 12y agoNow we all need is this as a SAAS (rest API) and create a jQuery plugin that given the parameters returns the corresponding CSS
- CmdrKrool 12y agoI know the web is not print, pages are not static, user screens vary and one shouldn't try to control everything bla bla bla, but it seems all my layout woes ultimately boil down to difficulty in lining things up. That's what 'layout' means after all, isn't it? Aligning one thing with another, to show they're related. I'm not a classically trained graphic designer, but doesn't any explication of visual fundamentals include 'alignment' somewhere up near its top? Yet CSS really, really sucks at lining things up. Anyone designing a better system might do well to start with the notion of alignment as a basic primitive/operator. To be able to say, item A here ought to line up with item B there (and if not possible, predictable behaviour C results). My gut feeling is that one could then derive all other types of layouts from there. I admit that might be naive. Also, I realise that I've probably just described constraint-based layout, but as yet I haven't tested one of its implementations such as GSS in a real project.
- deleted 12y ago[deleted]
- talmand 12y agoAs a classically trained graphic designer, I find the biggest problems to layout is more due to the fact that the display is completely unknown. It can range anywhere from hundreds of pixels in width/height to thousands of width/height in pixels. Not to mention the differences in pixel densities and orientations. If one were to consider these problems alone, CSS works quite well for what it was designed to do. Most designers I've discussed these problems with have problems more in their thinking than with the tool itself. They mostly try to apply print design thinking to web design, which simply does not work.
- amelius 12y agoMy personal trick is to position the content absolutely at 50% (both left and top), and then transform the content using a -50% translate in both directions. Works for dynamically sized content (and statically sized content as well, obviously).
- talmand 12y agoBut then people whine about no support for a six-year old browser.
- awalGarg 12y agoFor everyone who thinks CSS is just a collection of hacks (rightly so) etc., you should try playing with GTK+3. It borrows a subset of CSS, has it's own Flexy Grid model system etc. It will still be fair to call it a Work in Progress but I think it's layout system is quite nice.
- Kesty 12y agoAnd still the solution for centering a dynamic sized div is still using table-cell.
- zer0rest 12y agoThis is godlike.
- ocdtrekkie 12y agoThe fact that this site exists is confirmation that all of my "bah humbug" about using CSS over tables is pretty justified. And while CSS still renders differently in every browser, I have yet to find a browser that can't render tables consistently.
- toxican 12y agoTo save people a bunch of time, here's 90% of the comments: >Just use flexbox! Which is great, except it isn't supported at all by IE8 or 9 and is only partially supported in IE10 (by prefix only). Which means a lot of people simply can't use it. I'm hesitant to use it myself, and I've got a very lax policy on supporting old IE.
- DiNovi 12y agoMy company recently went all in with flexbox, and you should too. We had the same concerns, but even IE 9 is 4 years old at this point, and we decided we shouldn't be held back because of it. If a client wants IE9 support, they can pay extra. I have run into a few IE10 gotchas, but they're all solvable. IE10 just uses an older version of the spec. and IE itself will be cut loose from MSFT in a few months.
- throwawaymsft 12y agoIt's a business decision to limit forward progress to support browsers 3-4 major versions behind. One that multi-billion dollar companies like Google have decided isn't worth it. "A lot of people" = 4% on IE 8 & 9 (http://www.w3counter.com/globalstats.php http://www.w3counter.com/globalstats.php)
- toxican 12y agoReally depends on the business and their clients. If you've got a lot of corporate clients stuck on IE8/9, why disenfranchise them? Although I will say this has me re-considering flex.
- CodeSheikh 12y agoThis was not intended to be the entire solution but a great starting point (more than that) for someone (cough backend devs cough) who has been having issues with CSS centering.
- menssen 12y agoI often use this as an interview question for CSS people: "How would you vertically center a box inside another box." I like it because there's like four correct answers, each with drawbacks. The general answers, from worst to best, are usually: 1. margin: auto (wrong) 2. top: 50% (mostly wrong) 3. negative margin-top (correct if you know the size) 4. table-cell or translateY (correct) 5. a correct answer plus a discussion about why it has to be a hack FWIW, when you set everything to "Unknown", this site tells you to use display: table-cell. If you don't have to support IE8, I generally prefer "top: 50%; translate-Y: -50%" [Edited for spacing.]
- btbuildem 12y agoIt says something about the state of the art, that an issue so simple and essential as this generates such a wealth of commentary. We're a long way from home yet.
- ddade 12y agoA tutorial on how to center things? That's a pretty serious FAIL.