12 ms·
Centering in CSS
- LordDragonfang 6y agoSee also http://howtocenterincss.com/ http://howtocenterincss.com/
- porphyra 6y agoand the relevant HN discussion that hit the front page with over 1000 points: https://news.ycombinator.com/item?id=9405284 https://news.ycombinator.com/item?id=9405284
- Raed667 6y agoI have had this link bookmarked (and used) way longer than i will ever admit in an interview.
- greggman3 6y agoI've used that site. Doesn't work. Or rather it only covers a small set of cases.
- jaequery 6y agoIt’s not enough to explain just only css, we also need an equivalent using css frameworks such as bootstrap, material, and tailwind, since most use frameworks these days
- shhsshs 6y agoAre you implying that using a css framework somehow restricts/prevents you from also using normal css in some places?
- jaequery 6y agono. i was just simply implying it be nice if they also had a reference on how to center (both vertically/horizontally) using some of the major CSS frameworks built-in way 'without' resorting to raw CSS. kind of like a cheat sheet. because the problem i face is that there are just too many ways to center things and wish there was a most recommended method. i come across many articles explaining how to in raw CSS, but not too many using frameworks. i typically jump from one css frameworks to the next (bs4, material, tailwind) and writing custom css is usually frowned upon if there are already a way to do so built-in by the framework. but it's hard to keep up with these changes so thought it'd be nice if there were some guides or articles for them.
- slmjkdbtl 6y agohonestly cannot tell if this is sarcastic
- giantDinosaur 6y agoAt least for bootstrap, most of the relevant classes are essentially aliases for flexbox, so I don't see why it would be much use.
- onion2k 6y agoAn article about CSS shouldn't need to mention frameworks - it's the framework's job to explain how to use the framework. You wouldn't expect an article about lists in C to explain how to use arrays in PHP...
- mikepurvis 6y agoHands up for anyone else who remembers how much worse this was in the CSS 2.1 days when it had to be hacked using `display: inline-block` and tricks involving negative margins.
- mattwad 6y agoinline-block was cheating. Plus, for a long time after it was "released" you couldn't rely on browsers actually implementing it. I always used `margin: 0 auto` and if you know the height of an element, you can set the top to be 50%, and use a negative margin half its height.
- mikepurvis 6y agoI'm really hazy going back this far, but wasn't it that it worked in Firefox and Opera, but then IE could be handled using magic HTML comments that served it special separate rules? I know sometimes IE's vendor-specific CSS "expressions" system could be used to compute properties like max-width and so-on that it didn't otherwise support, and it was nice to be able to do that without requiring a JS polyfill.
- ljm 6y agoThere were conditional comments for loading IE specific things. And I remember IE6 having .htc files (html components), csspie is the one I remember
- npsomaratna 6y agoReminds me of having to use (CSS) floats to position stuff. CSS grid and flexbox have made positioning (in particular, vertical positioning) so easy.
- BattyMilk 6y agoFloats and clearfixes everywhere
- thekyle 6y agoI know it's not the trendy thing, but <center> has always done exactly what I wanted without much fuss. Even if it's technically depreciated, it's in such widespread use that no sane browser would ever remove support.
- userbinator 6y agoThe web development "community" seems to love reinventing increasingly complex solutions.
- BenTheElder 6y ago<center> and the solutions in this post are not equivalent ... The HTML center tag only horizontally centers the contents which you can do with the simple CSS: `text-align:center` [1] The examples in this post center horizontally AND vertically. [1]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ce...
- arn 6y agotext-align:center does NOT entirely replicate <center>. And has been a source frustration for many.
- BenTheElder 6y agothat's fair, but <center> and this post are still not equivalent at all.
- deleted 6y ago[deleted]
- markdown 6y agoNah, that's just the javascript nuts. We're much saner in CSS land.
- 6y ago
- dash2 6y agoReading articles like this, my basic impression is that, after CSS has been around for twenty years or more, it’s still complex to do simple things that everybody wants. Is this why the web is less successful than it might be?
- otabdeveloper4 6y agoFlex and grid finally made everything make sense. It's like I'm out of Plato's cave now.
- kristopolous 6y agoThere's a debate on the purpose of it. They problem is we took our interlinked document space and built thin client applications on it. Our crosslinked thoughtworld for intermingling intellects in practice is mostly an entertainment and shopping platform. Really they probably should have split off when it was young ... Replacing HTML with something for the original lofty goals and leave the html/css/js triumvirate for the mainstream use we all see now. Then there becomes no pretext that there's any intellectual, educational, or documentarian use for the web because there'd be something else, let's call it the Yeb for those purposes. It'd get two way linking, ontological markup, a WAIS like querying system (where the document author explicitly sets the search up separately from the document), etc. But that never happened and the web has way too much inertia to successfully fork it at such a fundamental level without a monumental multi-year effort so here we are with one set of standards trying to serve all masters at once by layering stuff on top of each other, building a bigger russian nesting doll to stuff our existing web into (could you imagine if say jstor or citeseer required a "yeb browser" because it served content that was fundamentally incompatible with the web standards. Could have taken off in 1995 but not now) The only engineering results those conditions ever produce is complexity since it inherently, by design, lacks the focus to remove it.
- hertzrat 6y agoThink of how much extra software engineers get paid because of how difficult it is to do simple things. If it were easy, you wouldn’t need a whole team for a crud web app. If everything didn’t break from updates constantly, you wouldn’t need SaaS in order to feel like a piece of software might still work in 2-5 years. It’s a weird thought, I think I got it from a Jonathan Blow stream
- greggman3 6y agoOne problem is there are always cases that aren't covered by these articles. Centering in CSS could be so many things. Center one element inside a another, Centering a css background image . Centering an inline element in a line of text to be centered vertically in the line. They all require different solutions For inline I'm not sure I ever found a solution I liked. I just wanted something like This brought to by <avatar> Name With the avatar the same size and centered similar to emoji faces. I'm sure it's easy but I couldn't find a solution that wasn't a hack of specific sizes (ie, not flexiable/responsive) https://jsgist.org/?src=2493f4279ba3efb1eb84587238afd3dd https://jsgist.org/?src=2493f4279ba3efb1eb84587238afd3dd
- russellbeattie 6y agoWhat in the flying fuck is a 'ch' unit? Took me a couple minutes to track it down. In the CSS Values and Units Module Level 3 Editor's Draft [1], it's defined as, "Equal to the used advance measure of the “0” (ZERO, U+0030) glyph in the font used to render it." Are you kidding me?? Please stop. You're not clever or cool using some random unit like this in an article about something completely unrelated (or ever, really), you're just being an asshole. I thought at first it was relevant to the techniques being shown. Idiot. 1. https://drafts.csswg.org/css-values-3/#ch https://drafts.csswg.org/css-values-3/#ch
- RobertKerans 6y ago"I was ignorant of this unit of measure so the author is an asshole" is spectacularly rude. What is your solution to specifying that a column should contain on average n characters in CSS? With your reaction, I'm sure you must have a solution than is simpler than just using the basic unit measure that CSS provides? Because the author isn't being "clever" or trying to be "cool" by just using the basic API provided.
- tannhaeuser 6y agoWouldn't it have been wiser to restrict CSS to document-oriented use cases, accepting that for apps you need Javascript anyway, and then just measure and position elements programmatically? The problem with the discussed solutions in TFA (which is great btw) is the lack of discoverability, and CSS generally solving for the wrong 20% of use cases, bringing unsustainable technical debt for displaying our docs going forward for generations to come. I really would appreciate an attempt to specify CSS behavior, even a subset of it, as a constraint-based formulation or other formal spec; easier said than done, though.
- onion2k 6y agoWouldn't it have been wiser to restrict CSS to document-oriented use cases, accepting that for apps you need Javascript anyway, and then just measure and position elements programmatically? Measuring DOM elements and moving them around in JS is quite slow. Transforms are fast, but understanding where things are after they've been transformed is hard. JS layout is also somewhat prone to problems with things like browser zoom level, OS display scaling (although I've not seen that be an issue in a couple of years), differences between browsers and browser versions, and so on. Layouts with CSS, so long as you're being reasonably conservative, do work quite well in 2020.
- Yaggo 6y agoI agree that there's lot of benefits and certain elegancy by sticking with CSS layouts. CSS transforms are really just an visual effect, not affecting the layout. That's why they are super fast (typically HW accelerated by GPU), but not suitable for defining the layout. Managing the DOM in JS may be order of magnitude slower but is still fast enough, actually surprisingly fast. It's common to implement 60 FPS animations e.g. in React. Of course the performance heavily depends whether the manipulation causes a layout reflow etc, but generally speaking, DOM is pretty fast nowadays, and most sites/apps are not _that_ performance critical (such as games). Yes, it's not uncommon either that a complex JS app becomes slow, but that's mostly because of inefficient programming / generally bloated app, not because the layout is done by JS instead of pure CSS. Browsers already have "alternative" APIs to make totally non-DOM interfaces, such as canvas (2D) and WebGL (3d). Nothing prevents to come up with alternative layout/UI libraries written on top of them. I'm sure such a libraries exist. Why it's really rare to utilize non-DOM UIs is probably due to many reasons, i.e. compatibility issues with exotic/older user-agents, devs being more familiar with DOM based solutions, etc. After all, I think DOM works pretty well even for app-style UIs. Actually, many "native" technologies don't offer as easy responsive layouts, user-settable font-size, etc, which comes almost for free with DOM. There's lof of beauty in the DOM, despite its document-oriented origins. (Oh, I just typed out some mind flow of mine, maybe a bit off-topic.)
- meerita 6y agoIve been developer for 24 years and I can remember the hell it was centering stuff even prior to CSS world. From the example, I don't like the way he used flex on grids to maintain children aspect ratios, better to use grid's container optiones like justify-items.
- deleted 6y ago[deleted]
- parisianka 6y agoDid not even hear about some tips
- _0o6v 6y agoWhat on earth did I just read? "Pop and Plop"? "Gentle Flex"? "Autobot"?
- pickledcods 6y agoCSS "visual formatting" was broken since day 1 due to inconsistency. Take for example "height: auto", a key component in vertical (absolute) positioning. According to section 10.6.4 "Absolutely positioned, non-replaced elements", "height: auto" is the height based on the content except when top and bottom are both auto and it suddenly changes to the the height of the containing/parent element. This breaks vertical alignment based on content. Also in the same section, if height is auto, then a top or bottom of auto is calculated, unless both are auto and then suddenly top is set to 0 instead of spreading evenly. For that you need to use margins, but they only work if top, height and bottom are all non-auto. As a result millions of developer hours have been spent on frustrations, fixups and workarounds.
- ChrisMarshallNY 6y agoThese are useful. #5 is one that I like. In the past, I’ve had to specify concrete sizes for elements, then set margins of minus half that value. This is better. I would like to be able to do the same type of thing for background images, but this technique could give me the same effect.
- Taig 6y agoUnlike the other methods, absolute positioning + translating has the advantage that you can not only center the child, but give it a percentage position within its dynamic parent. This can be especially useful when the position should be animated. https://medium.com/swlh/dynamically-position-and-center-an-html-element-with-css-based-on-percentage-5fea0799a589 https://medium.com/swlh/dynamically-position-and-center-an-h...
- krsdcbl 6y agoBig caveat, this only works when the container has a defined size as you are removing the centered child from element flow
- nkozyra 6y agoI think as late as 2005 there were moments where I just said "screw this I'm using a table" while everyone screamed about how that's semantically wrong and what you really need is an elaborate series of hacks and misuse of CSS properties. Flex and grid was the moment I cared about doing things right. Even now I use grid a lot because I find it works as well in 3d as 2d and I get CSS disciples trying to correct me.
- Taig 6y agoIt definitely isn't as versatile as the champions of centering from OP's article. But it's a related use case that the other techniques cannot solve. And of course the approach can be varied to some extend: https://jsfiddle.net/31gftbxs/ https://jsfiddle.net/31gftbxs/
- blntechie 6y agoMaybe unrelated but can someone help me point to a good place to start learning CSS by really understanding it at fundamental level. I have had start and stop bouts of learning CSS several times before and I couldn’t understand it logically like other languages or frameworks for reasons I can’t clearly explain. I avoid frontend programming mainly because I don’t know CSS.
- 8lall0 6y agoI always follow this personal rule for centering: - Buttons and stuff that should stay the same with font increase: padding with ems - Everything else: flexbox Flexbox has made everything so easy.
- graup 6y agoSurprisingly concise and fun article! I hadn't seen the "Fluffy Center" technique before. I'm not sure I really get it though – the video and the text showing different code is only adding to the confusion. Is it 15vmin or 10ch? What does "Word space is gap" mean?
- mwexler 6y agoI get TIMTOWYTDI, that it's good to have more than one way, but each seems equally inscrutable. Can you imagine explaining any of these to a novice who just wants that box to be centered and stay centered? When they ask "Why is there no simple 'alignment:center' option for the named thing?", what can we say other than "but look at all this jargon with the word 'center' in it! Easy! Now go back to your selectors!" CSS always feels like less of a languages and more like a bunch of hacks crammed into the browser. And the inscrutibility leads to copy-pasta code: search for a sample, paste it, it works now, mostly... But when it breaks, newbie dev will struggle to untangle. (Ruefully, speaking from experience). I know, many folks love css, but I find it a big mental discontinuity from html and js. It's solving a different problem, sure, but I look forward to some future version of styling which might offer a more "readable" experience.
- chrisweekly 6y agoI sympathize. Been doing webdev since 1998 (before CSS). Most CSS in the wild is just awful and virtually unmaintainable. I can't recommend highly enough that you and everyone else (the overwhelming majority) who feels the same way head to https://every-layout.dev https://every-layout.dev to learn about "Axiomatic CSS". It explains and illustrates not just layout but virtually everything you need to know about leveraging standard CSS, building up from clearly-articulated and unimpeachable first principles. The axioms and examples on the free site are profoundly useful, and the $100 book / full site / component generator are more than worth it. Disclaimer: No affiliation, just a grateful customer hoping these ideas catch on.
- marlowe221 6y agoThanks for posting this. As someone new to professional web development, stuff like this is a valuable resource.
- spinningslate 6y agothanks - you've just sorted my Christmas project for me. I've tried to wrap my head around CSS layout several times. On each occasion, I've come away with a perplexed sense of "but.... surely it shouldn't be as hard as this?". Layout is about the relationship among elements. CSS - as far as I could see - is based on styling elements within containers. There's little or no ability to express peer-to-peer relationships directly. First example on every-layout and already I have a fresh perspective. For example, under stack [0]: "margin is really a property of the relationship between two proximate elements. " and then a solution for styling the relationship directly. [0]: https://every-layout.dev/layouts/stack/ https://every-layout.dev/layouts/stack/
- pluc 6y agoRemember when <center> was all you needed? Maybe with a valign'd table if you wanted to get fancy.
- woodrowbarlow 6y agoremember when `text-align: center` was all you needed? maybe with a `place-items: center` grid if you wanted to get fancy. (the vertical centering has always been the not-so-straightforward part. horizontal centering has always been easy. the current CSS techniques are just as easy as the HTML-only techniques you describe.)
- chrisweekly 6y agohttps://every-layout.dev https://every-layout.dev is the definitive guide to CSS layout from first principles. Webdev since 1998. This is a hill I'm prepared to die on, so to speak. It should be required reading for anyone doing web UI work.
- zild3d 6y agoIt's a nice resource, not going to argue that, but most of it is behind a paywall which makes it hard for me to make a go to recommendation. I lean more towards a flexbox guide [1] or game [2] [1] https://css-tricks.com/snippets/css/a-guide-to-flexbox/ https://css-tricks.com/snippets/css/a-guide-to-flexbox/ [2] https://flexboxfroggy.com/ https://flexboxfroggy.com/
- AltruisticGap2 6y agoWow VisBug is really interesting. Never heard of it.
- calibas 6y agoI like how much <center> is frowned upon by the experts, but when you actually inspect how sites are centering things, it's surprisingly common. Don't worry, I'm not gonna scold HN, I actually don't think it's that bad of a practice as no browser will ever stop supporting it. The experts can look down upon it all they want.
- ivanbakel 6y ago>I actually don't think it's that bad of a practice as no browser will ever stop supporting it It's not a bad practice to use center because it's not HTML5-compliant (though that's not a bad reason to avoid it). It's bad practice because putting purely visual info in your semantic markup is a bad idea - mixing responsibilities between different layers creates pain points for later work. In this sense, it's like a GOTO. It'll work well enough for one person on a small project, and you might thumb your nose at the experts who tell you it's a bad idea - but it's a source of technical debt, and the better approach is to just avoid it from the start.
- calibas 6y agoAnother perspective: It's bad practice to constantly change everything every few years, then expect everyone to upgrade to the latest and greatest technology or get left behind. It's good practice to use code that runs just fine on a 20 year old system.
- ivanbakel 6y agoAnd yet the change to <center> is not "a few years old". It was deprecated back in 1997 as part of HTML4, because it was never deliberately introduced as a standard tag - <center> only exists because Netscape Navigator was once influential enough to force tags into existence, and it did so, even though the concept itself was flawed. Centering HTML elements through CSS has existed since 1997 as well, specifically because CSS aimed to make those HTML extensions, that Navigator had introduced, obsolete. Standards bodies sometimes have to make the tough decision of breaking with the past to safeguard the future. Software longevity is a worthwhile cause, but protecting a 23-year-deprecated, non-standard HTML tag, whose use is bad engineering, is not the kind of hill I would die on.
- flowerlad 6y agoThis code is very inefficient: .autobot > * { margin: auto; } Browsers match CSS selectors right-to-left. Because there is a * at the end, this rule has to be matched against every element. More info: https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left https://stackoverflow.com/questions/5797014/why-do-browsers-... https://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/ https://www.stevesouders.com/blog/2009/06/18/simplifying-css...
- nerdkid93 6y agoFrom my personal experience, CSS performance isn't really that much of a concern in the world of modern browsers. Maybe IE11 would hiccup on a particularly large page with 1,000s of DOM nodes, but all of the evergreen browsers are ridiculously performant with CSS. I'm not saying you should write queries like that, but if you must (for readability or technical reasons), it likely won't harm your site's performance.
- ArtDev 6y agoThis is a non-issue with modern browsers.
- partiallypro 6y agoI've used this tool fairly often, it will generate the code you need to center based on your browser requirements, etc http://howtocenterincss.com/ http://howtocenterincss.com/ I basically only use flexbox now, but even flexbox does some really stupid things I don't get. Like if you want one element to go against the parent's rules of say, aligning left, you set the left margin of the object you want going right to "auto" which will push it and every object after it right. But this can create some annoying problems.
- user00012-ab 6y agoJust use "<center>data</center>" seems to work every time.
- swyx 6y agoit's super briefly mentioned in the post, but just want to highlight that you can center in CSS grid with 1 extra line of CSS: .parent { display: grid; place-items: center } and it's supported everywhere CSS grid is! My biggest TIL of the year. More 1 liner tricks from Una Kravets here: https://twitter.com/swyx/status/1279674027070504961?s=20 https://twitter.com/swyx/status/1279674027070504961?s=20