7 ms·
How to Center in CSS (2015)
- _bxg1 6y agoThis is a straw man. Today you can simply use flexbox on the container: display: flex; justify-content: center; // horizontal align-items: center; // vertical Doesn't work in IE without a JS polyfill (which is available), but has worked in all other browsers for six years or so.
- petepete 6y agoFlexbox (and grid) have made frontend work tolerable again for me. You can do in a handful of lines what used to take all kinds of jiggerypokery, hacks and extra markup to wrap things.
- pjmlp 6y agoFor me as well, specially grid, since it was originally submitted by XAML team and is heavily influenced by its grid layout engine.
- account42 6y agoThat is exactly the code the website will generate if you select no IE support.
- _bxg1 6y agoYet it opens with this misleading blurb: > Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors. Which is no longer true in the great majority of cases.
- frabert 6y agoWell it's not true if you decide to ignore the fact that this does address the situations in which centering is a pain in the ass. If you exclude all the factors this takes into account, it obviously becomes trivial.
- TylerE 6y agoIt is always the minority of cars that kill you. If it only has to 95% work, that’s always been easy.
- breakingcups 6y agoThat's only misleading if you don't have to support IE. I'm guessing that's the case for you but many of us still have to. Also, this site seems to have gone up in 2015 and hasn't changed (substantially) since. I also don't think you're correct in calling this a straw man. This is not a debate and there was no other party whose assertion this site seems to refute, so calling it a straw man doesn't seem to fit.
- cris-ward 6y agoActually it also works in IE11, as it should. Flex does work in IE11 with some known bugs - https://caniuse.com/#search=display%20flex https://caniuse.com/#search=display%20flex
- njsubedi 6y agoYes, with flex we don't need anything else. If flex is not available, the browser is supposedly too old to care if we used tables for layout so I'll just throw in `display: table-cell`.
- soperj 6y agothat can cause some issues in Chrome oddly enough, depending on how you're using it.
- deleted 6y ago[deleted]
- RyanGoosling 6y agoWhat does a JS polyfill have to do with CSS? Also, try that out in IE 11 without a polyfill. This works in IE without a JavaScript polyfill (lol): <html> <body> <div style="width: 400px; height: 400px; background: red; display: flex; align-items: center; justify-content: center;"> <div>TESTING</div> </div> </body> </html>
- NeutronStar 6y agoI have to support IE8 at work so this wouldn't work.
- alisey 6y agoAnd yet six years later still no widespread support for the 'safe' keyword. Which means the content can overflow the container without a way to scroll to some parts of it: https://jsfiddle.net/r50qseah/ https://jsfiddle.net/r50qseah/
- aerovistae 6y agoWhat is the 'safe' keyword?
- alisey 6y agohttps://drafts.csswg.org/css-align-3/#overflow-values https://drafts.csswg.org/css-align-3/#overflow-values
- deleted 6y ago[deleted]
- ChrisMarshallNY 6y agoHere's what I've been doing for years (The <div> can be any element, like <ul>): <div id="wrapper" style="text-align:center"> <div id="wrapped" style="display:table;margin-left:auto;margin-right:auto;text-align:left"></div> </div> WFM YMMV
- mattwad 6y agoyou really use the same id twice on a page?! Heresey! Also.. I do the same (essentially: margin: 0 auto) but it works with display: block too, and you don't need text-align center on the parent.
- bzb3 6y agoIt's not the same id: wrapper vs wrapped
- ChrisMarshallNY 6y agoThey were not IDs. They were indicators of what the div is for. It was sort of HTML-pseudocode. In any case, this is exactly how you center something that doesn't try to stretch across the entire page. It's old-fashioned, but robust. Also, I would generally not use inline CSS. I think of it like I think of !important: the nuclear option. That said, I tend to use inline styles a lot for WordPress site content, because I don't want to deal with the slow-ass "customize" option.
- RyanGoosling 6y agoYou don't need the style="text-align:center" on your wrapper element
- ChrisMarshallNY 6y ago> You don't need the style="text-align:center" on your wrapper element Why not? The goal is to center something with an unpredictable size. display:block adapts to the container. display:table adapts to the contents. This uses both.
- jacobedawson 6y agoHaving to still support IE 11 for most projects, I really like the following: div { position: absolute; right: 50%; bottom: 50% transform: translate(50%, 50%); }
- onion2k 6y agoIE11 supports most of flexbox. You don't need hacks.
- jacobedawson 6y agoforgot the <
- RyanGoosling 6y agoIt's time to learn flexbox
- cosmotic 6y agoIt's too bad flexbox isn't as easy to understand as box model; that puts the breaks on adoption, regardless of how well it handles the centering scenario.
- onion2k 6y agoFlexbox is far simpler than the box model.
- dirtnugget 6y agoBox Model is a living mess
- johnchristopher 6y agoI am not into the CSS game anymore, if anything needs to be done I'd just go with whatever widgets any CSS framework offers, but why has it been so hard for so long to center things with CSS (I believe flexbox finally fixed it) ?
- onion2k 6y agoFlexbox did fix it, and it's been available in Chrome since 2013, Firefox since 2014, and everything else since 2015. IE 11 supported enough of the 2012 syntax to be usable. Even IE 10 supports some of it, albeit poorly.
- johnchristopher 6y ago2015 ? Yeah, I think I remember hearing about flexbox around that time, also when I stopped doing any CSS work (which I had started around ~2000 I think).
- mrweasel 6y agoI just throw a <center> in, it works well enough for most cases.
- laurentdc 6y agoI prefer <center style="text-align: center;"> for maximum centeredness
- RyanGoosling 6y ago
- stblack 6y agoPinboard tells me, I "previously saved april 2015". So I bookmarked this more than five years ago. Back then, this site was addressing a big problem and, to some degree, it's still a confounding problem sometimes. So high-five to its creator. And to the HN haterz in these comments, take a hike.
- scrumbledober 6y agoSaw the link was already clicked and was curious. I've still got this page bookmarked in chrome from when I was first starting out as a web developer.
- growt 6y agoIt doesn't solve vertical centering, but I am secretly still a fan of the center-tag. Just does what it's name implies in most situations. I still don't get why its avoided like the plague.
- RyanGoosling 6y agoIt's avoided because it's obsolete and is not in the HTML5 spec: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ce...
- blauditore 6y agoI've been doing HTML for ~10 years and have never seen this before. Apparently, it was deprecated with HTML4 already, though I'm not sure why.
- freefal 6y agoProbably the same reason that <b> (bold) and <i> (italics) aren't used anymore. There's now a clearer delineation between document structure (described via tags) and style (described via CSS) than there was in the earlier HTML specs.
- 6510 6y agoIf you allow user generated input it is fine to allow <center>, <b> or <i>
- Semaphor 6y agob and i are back though, but a little different ;) > The b element represents a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance and with no implication of an alternate voice or mood, such as key words in a document abstract, product names in a review, actionable words in interactive text-driven software, or an article lede. and > The i element represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose in a manner indicating a different quality of text, such as a taxonomic designation, a technical term, an idiomatic phrase from another language, transliteration, a thought, or a ship name in Western texts. [0]: https://html.spec.whatwg.org/#the-b-element https://html.spec.whatwg.org/#the-b-element [1]: https://html.spec.whatwg.org/#the-i-element https://html.spec.whatwg.org/#the-i-element
- mpawelski 6y agoCentering in CSS is "solved" problem if your "worst" browser to support is IE11. Flexbox does the job there. However, there are still couple of common tasks that are pain/hard/impossible to do with just CSS. Recently I learned that after all this years you still need to use JS to get css animation for dynamic height ("height:auto") of elements. And there is no progress in fixing it at CSS standard level. It's just sad... https://github.com/w3c/csswg-drafts/issues/626 https://github.com/w3c/csswg-drafts/issues/626 https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css https://stackoverflow.com/questions/3508605/how-can-i-transi... https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css https://stackoverflow.com/questions/3508605/how-can-i-transi...
- pedrogpimenta 6y agoThere are some tricks you can use if you know the max possible height your element can have, but it's not great, yeah. Edit: Oh, I just saw that the stackoverflow question you linked has this for the accepted answer :)
- Wowfunhappy 6y agoThe problem is the animation speed is overly fast if you're at less than that maximum height.
- 6510 6y agoA wise man once said (me): ill use <center> until the end of time and thy browsers shall support it. (did of course learn the new and improved ways to qualify the ignorance)
- MattGaiser 6y agoGoogle’s home page uses it three times.
- perilunar 6y agoHN wraps the whole page in a centre tag.
- carapace 6y agoI was explaining this to a normal person the other day, and maybe I'm doing it wrong, but it was impossible not to make it sound like we are weanies. I mean complete knee-biting berks. "What do you mean centering was hard?" "Not was, still is." "..." "yeah. ..."
- otabdeveloper4 6y agoSilly human! One does not simply center in CSS.
- mouzogu 6y agoOne which I came across recently, a little smaller than the usual flex solution: .v-h-center { display: grid; place-content: center; }
- c-smile 6y ago12 years ago at W3C styles I've proposed to solve it as simple as this: .in-the-middle { width:max-content; height:auto; margin:*; // "coils" on all sides moving it // to the middle of free space in container } So these tons of tools, essays and doctoral dissertations on "how to center stuff" would not be needed. Here is the story: https://terrainformatica.com/2018/12/11/10-years-of-flexboxing/ https://terrainformatica.com/2018/12/11/10-years-of-flexboxi...
- deleted 6y ago[deleted]
- diablo1 6y ago<div class=element></div> <style> .element{ position:absolute; width:500px; height:500px; left:50%; top:50%; margin-top:-250px; margin-left:-250px; } </style>
- viklove 6y agoDon't do this, you will run into edgecases that make things look jank. Use flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ https://css-tricks.com/snippets/css/a-guide-to-flexbox/
- diablo1 6y agoThanks for the tip. Any particular browser that causes such 'jank'?
- Chyzwar 6y agoThis would center a fixed sized element in absolute position to page, this was never an issue. Problems start when you do not know size of your element and its parent. Flex finally fixes[1] this issue but it was not fully supported until recently[2]. [1] https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ https://philipwalton.github.io/solved-by-flexbox/demos/verti... [2] https://github.com/philipwalton/flexbugs https://github.com/philipwalton/flexbugs Most of the flexbugs are now fixed and flex should be recommended way of making layouts.
- colejohnson66 6y agoThis requires advanced knowledge of the width and height of the `.element`