48 ms·
How to center a div in CSS
- t1c 3y agoI've been doing webdev for a while and this is by far the best "centering a div" article I've ever seen.
- PreInternet01 3y ago[flagged]
- JimDabell 3y ago> Oh, no, please, not another "centering content using CSS is really, really simple: it's just you that is dumb" think-piece... That doesn’t resemble the article in the slightest.
- PreInternet01 3y agoThe lead-in to said article: "For a long time, centering an element within its parent was a surprisingly tricky thing to do. As CSS has evolved, we've been granted more and more tools we can use to solve this problem." ...yeah, but still none of these tools like, actually work?
- Etheryte 3y agoIt sounds like you didn't even read the article, the contents are nothing like what you describe.
- PreInternet01 3y agoWhat about "[...] centering an element within its parent was a surprisingly tricky thing to do. [now...] more tools we can use to solve this", and the subsequent complete lack of a list of these tools that work cross-browser did I miss?
- ok123456 3y agoWas the <center></center> tag really that bad after all?
- sonofhans 3y ago<center> is a text-level element, not block layout control.
- ok123456 3y agoIf you allowed it to control blocks, you could consider it a semantic tag with reasonable defaults.
- system2 3y agoYou can't modify this without touching html. Just create a div and assign class so you only modify CSS later.
- ok123456 3y agoWhat would stop it from being styled by CSS in the same way? You could use it for semantic markup.
- system2 3y agoIt would be messy. If <center> element is used somewhere else then you will have to find its parent classes. If they don't have proper parent div classes or <center> used in many places then you will have to individually target <center> elements like div > div > div > center and another one div > div > div > div > center. You can override center too but why would you try that instead of creating a class for a div and addressing it properly. Classless elements cause long-term issues when modified with CSS.
- dylan604 3y agoso how do you center that vertically? I consider it only slightly less offensive than <blink> as being useless. I also find it incorrect from attempting to have the markup dictating the layout. Sure, this was before CSS was robust, but it is one of the reasons that I just had no problem with it going the way of the dodo.
- bradley13 3y agoThe "how to center" is a classic question for CSS. The fact that it is not blindingly obvious is indicative. CSS is a miasma. A kitchen sink collection of stuff designed, not by one committee, but by several committees simultaneously. They have long since given up on actual releases. Instead, the current state of CSS is a collection of states of individual modules, all of which are under continual change. This is not how you develop software. Or anything, really. /rant
- wvh 3y agoI both agree and disagree. This is just how how larger groups of humans work, slowly and chaotically. Herding cats. It's also not clear where we're collectively going with the web and all of its technologies, so there will be lots of failed experiments and disagreements. There's a much broader scope here than a well planned engineering project with a clear goal and path.
- deleted 3y ago[deleted]
- dpedu 3y agoRegarding centering - eh. I think this question comes up so often because it is simply the natural question to ask. What are the first things someone learning how to make a web page visually look how they want is going to learn? Probably text size, color, background color, and alignment. All of these except alignment translate pretty much 1:1 from pre-css days. Color on the body tag, size/color on the tag surrounding the text you want styled. Or, css color/font-size property on the surrounding tag, or background-color on the body. All very similar. Prior to CSS, if you wanted content centered, you just slapped it in a <center> tag. Didn't matter if it was text or html objects like divs, tables, buttons, etc. IMO too many people expected CSS to work like what we had in the past - no distinction between inline and block objects - and when CSS didn't fit their pre-conceived mental model, these questions came up. And centering just happens to fit in the niche of being basic enough that beginners want to know about it.
- wruza 3y agoAccording to this, most CSS issues boil down to “you don’t know CSS and have a wrong mental model”. Well, if most people who enter it have a wrong mental model, it’s not their fault that the “correct” model is absolutely alchemic in its nature.
- max-throat 3y agoThe fact that centering a div in CSS basically requires a doctorate is the entire reason I gave up on web dev.
- notfed 3y agoI empathize! It used to, but no longer, so give it another shot! :)
- dbbk 3y agoIf you think flex centering is the equivalent of "requires a doctorate" I'm not surprised you weren't cut out for web dev
- dylan604 3y agoSo for those of us that consider this dead simple, can we just start adding CSS Ph.D on our CVs?
- chihuahua 3y agoNo, you also have to throw away 3-6 years of your life.
- dylan604 3y agoI don't know about that. I'm not a UI person, yet I feel like I have a pretty good grasp on CSS. I actually like it. So when I'm sick and tired of programming things, I've found myself recreating the layout of some site I liked by writing the CSS/HTML by hand. You learn pretty quick that way. It's a shame that all UI is now only allowed to be done with some library or other.
- chihuahua 3y agoI was referring to the observation that getting a Ph.D. usually requires wasting 3-6 years of your life doing something tedious and useless (source: my time getting a Ph.D. in computer science)
- entropie 3y agoEvery. Time. Man. I love his posts. So much information and insight. But why the hell does a guy obviously so good at UX stuff fuck around with my scrolling? I cannot stand it.
- charliebwrites 3y agoCan somebody explain to me why centering a div is such a challenge to have an easy implementation for? It seems like Browser makers, Languages creators, and developers all have a pretty strong incentive to solve such a fundamental, basic problem in web development to make the design experience easier. Why haven’t these groups come together to make an easy solution to this? What am I missing?
- JimDabell 3y agoBecause what people mean by “centring” varies depending on context. You are actually talking about a group of several different behaviours and you don’t always want the same one. So you need multiple behaviours, and you need multiple ways of specifying those behaviours. The most obvious example: horizontal and vertical centring are different because our writing system has a specific direction it flows in. You can’t just do the same thing for horizontal as for vertical because text doesn’t work that way.
- hnlmorg 3y agoThis problem was solved literally decades ago with <center>. I appreciate why that HTML tag was deprecated but I also completely sympathise with why people scoff at the complexity of doing the same thing with CSS.
- nicoburns 3y ago<center> only centers horizontally which has been easy with CSS for years. It only gets tricky when you also want vertical centering.
- hnlmorg 3y agothis blog post and subsequent discussion is literally just about horizontal centring! I’ve been building websites longer than most (since 1994 in fact) and centring in CSS is definitely not as easy as it was with the <center> HTML. Not even close. If it were, there wouldn’t be this entire discussion to begin with. I swear the amount of times topics like this come up and yet a small subset of developers, likely Stockholm syndromed into believing things are great, is ridiculous. The sooner people like yourself pull your head out of your arse and realise that the current status quo is unacceptable, the sooner web standards finally mature into something that doesn’t have more footguns than the worst of C and worst of Perl combined.
- lofaszvanitt 3y agoThis guy's page never pops up in google search... My only problem is, that sidekick on the page is quite irritating. Can't we have some kind of furry fantasy creature instead?
- xnx 3y agoIt's taken decades for CSS to come up with anything as workable as putting content in a centered table. Yet during that same period, use of tables was shamed for layout.
- Alifatisk 3y agoI found using tables to be the most robust way at the time
- rad_gruchalski 3y agoNostalgia. I remember those days, 2000+ lines long tables written by hand in notepad on Windows 98 and served with PWS. Those were the days.
- cpach 3y agoTry ‘View Source’ on HN :)
- Alifatisk 3y agoNo way!!!
- mistersquid 3y ago> Yet during that same period, use of tables was shamed for layout. Tables for non-table data are not semantic and break accessibility. There is more to web development than where content lands on a page, which is only part of why good web development is hard.
- chiefalchemist 3y agoAnd good web development is harder because still too often web design is done by designers who don't have enough understanding of web development. My gawd, just earlier today I saw a help wanted that said "...PSD to pixel perfect..." I would have laughed if I wasn't already crying. "This is my life" and then the tears kicked in.
- tambourine_man 3y agoThe article is great. His avatar popping up mid scroll did “startle” me, though. A bit creepy sneaking in slowly from the edge. But it's effective, for sure.
- latexr 3y agoAs far as “subscribe to the newsletter” prompts go, that wasn’t as annoying as what I usually see. Still, would prefer it to have been on the right side so it didn’t obscure content.
- b450 3y agoWow, all these "why is this still so hard" complaints feel so off-base to me! As the article says, Flexbox straightforwardly solves centering in every simple case. When it doesn't solve it for you, you're doing something more complex than _just_ centering, so it's inappropriate to expect that the implementation will be dead simple.
- vogtb 3y agoThis is super true. Whenever I find myself struggling w/ flexbox it helps to take a step back and solve it one step at a time. Working my way out-to-in, parent-to-child element, and it becomes so much easier. There's a skill to it, but it's basically just elastic algebra.
- karaterobot 3y agoYep, there was a time when it was moderately difficult in certain cases, but it's been a solved problem for the last decade or so. You still hear people acting like centering DIVs in CSS is something like a cross between alchemy and rocket science, which is perhaps indicative that people don't follow CSS with the same attention as other parts of web development—yet they still feel comfortable making these statements!
- agumonkey 3y agogrid and flex were very nice semi malleable additions, they really lift the legwork and in the 10% of complex cases you can spend your brain time with joy
- Someone1234 3y agoFlexbox is what I always wanted CSS to be, but for a long time wasn't, until one day it was, and we could drop support for browsers without it. Feels almost end-game for CSS. There was a reason people loved Bootstrap's grid system so much, Flexbox does all that and more straight in your browser. Cannot over-express how much I love it.
- thr33 3y agoI too love flex but your comment is a bit off. bootstraps grid system is a fake grid modelled on flex. building layout grids with flex in general is definitely not endgame, its actually very tedious and unreliable. css grid however is perfect for this and represents one of the most underutilised powerhouses in the css kit
- ComputerGuru 3y agoI haven’t found a way to center a div with a background color containing text such that when the text wraps the overflow space (tried to expand horizontally to this size but ultimately needed to wrap) ends up being reclaimed (not background colored). Without forcing text to wrap at a certain width if it might still fit on one line.
- pkoiralap 3y agoI love this article. Especially the interactive aspect of it. Big Kudos. Also something I have been using since forever that almost always does the trick for me: http://howtocenterincss.com http://howtocenterincss.com
- ghoomketu 3y agoReally nice tutorial. On a related note, can somebody tell me how to make a nested div overflow (scrollbar) without specifying the height of all the parents divs? <div style="height: 100vh" id="one"> <div id="two"> <div id="three" style="overflow: auto"> I need </div> </div> </div> This is a rather simple example, but sometimes the divs are nested really deep inside and unless I specify all the childs divs as 100% height there is no scrollbar. This causes me a lot of issues.
- FooBarWidget 3y agoI solved this a while ago. If memory serves me correctly, you need to set overflow none on div two. Of this doesn't work, let me know and I can check my codebase next time it's convenient.
- allannienhuis 3y agoI'm too lazy/busy to confirm/test this, but providing a new stacking context on the parent by either by adding a position: relative (or whatever) or adding transform: translateZ(0) (or X or Y) avoids the need to specify every parent's height. Someone less lazy than me could confirm :)
- cfj 3y agoI'm just as lazy as you, but I just wanted to point out that you can create a new stacking context explicitly with isolation: isolate;
- allannienhuis 3y agooh, great tip - thanks! That's much more explicit. The other approaches have the new stacking context as almost a side effect.
- lxe 3y agoAlways learning something new from Josh W Comeau
- juliusdavies 3y ago<table align=“center”><tr><td><div>Here you go!</div></td></tr></table>
- desertlounger 3y agoClassic!
- divbzero 3y agoI prefer the simpler: <center>Here you go!</center>
- UberFly 3y agoCan't count how many times I've searched centering in divs over the years.
- ChuckMcM 3y agoNice article, the comments here are kind of amazing for a nominally technical audience. It is almost as if people have no idea how difficult automatic page layout and formatting is. There are literally PhD thesis topics on it[1]. And to expect that complexity to be abstracted away into some sort of simple "do-what-I-mean" expression? That just isn't going to happen. Go look at Gwern Branwen's web site[2]. That is art. But the trick is decide how you want the site to look and then constraining your written material to be expressible in that style. I've been looking at web page layout since 1995 when I joined a startup that was doing the "first magazine on the web about Golf!"[3] When the Zen Garden folks did their web site and started the 'A List Apart' mailing list which is now a website[4] it really helped me understand just what one was up against if you wanted to produce web content that rendered nicely on a wide variety of projections. And yes, the term projection is intentional because the function of going from semantic content to presentation on a screen or paper or other flat surface of finite size, is a mapping (or projection) from a native space into the rule set of the destination space. That rule set consists of both physical constraints (pixels per inch, total pixels horizonally and vertically, color capability) and software constraints (how much of the underlying capability can the browser software that is currently running express). Not to mention that every browser wants to do their own special thing. So yes, CSS is a "hot mess" for people who decide one day "I'm going to build a web page from scratch." And yet, that mess is really just an abundance of choices rather than constraints on what you can do. The process is the same for everyone, find the tools that help you achieve the results you want and then package your material into a form that you can easily convert that into that look. [1] https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=thesis+dynamic+page+layout&btnG= https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=thes... [2] https://gwern.net/ https://gwern.net/ [3] It was called Golfweb and eventually ended up being part of CBS Sports apparently (golfweb.com sends you there) [4] https://www.alistapart.com https://www.alistapart.com
- robmccoll 3y agoI recently spent a few days hacking flow-based layouts and pages into a flex-box-based layout system, and I can confirm that layout and formatting is hard. Figuring out how and when to shift elements to the next page, especially when you have a table with columns containing text and objects of different sizes, is a challenging exercise in picking good heuristics.
- borbtactics 3y agoThe demo containers and their animation are so cool and useful.
- mstudio 3y agoGreat article. Love the interactivity. One thing that really helped me understand CSS positioning (and centering) years ago was reading about the box model. Understanding the box model helps you determine flow within the DOM. The `display` and `position` CSS properties are also fundamental to learning about positioning. MDN has great articles on these! https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_... https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layou...
- system2 3y agoI was about to yell "Another basic CSS guide" but I was proven wrong. Every annoying centering issue is addressed in detail. Very well written.
- alex_suzuki 3y agoThanks for the amazing article, Josh! I‘ve come to use your CSS reset on a regular basis: https://www.joshwcomeau.com/css/custom-css-reset/ https://www.joshwcomeau.com/css/custom-css-reset/
- ramoz 3y agofor the uninitiated: <div style="display:flex;justify-items:center;align-items:center"> <div>I'm centered</div> </div>
- SarahC_ 3y agoThat doesn't work on Codepen.io, in the latest Chrome. Back to the drawing board.
- ramoz 3y ago<div style="display:flex;justify-content:center;align-items:center;"> <div>I'm centered</div> </div> * I wrote the original without testing but it is justify-content, not justify-items... oops
- ramoz 3y agohttps://codepen.io/backnotprop/pen/qBvzpvr https://codepen.io/backnotprop/pen/qBvzpvr
- retrochameleon 3y agoFrankly, I would probably just use flexbox for any centering use case. It's simple, fast, and straightforward. As far as I understand, flexbox has a pretty well optimized implementation, so it's not really a performance concern to just throw in another flexbox. Why would you not use it?
- jfengel 3y agoI often don't understand what flexbox is doing when what's inside is itself complicated. I think that fits-content might help, because I haven't tried that.
- retrochameleon 3y agohttps://css-tricks.com/snippets/css/a-guide-to-flexbox/ https://css-tricks.com/snippets/css/a-guide-to-flexbox/ I honestly don't understand why people would find Flexbox hard to understand. Yes, there's a little bit of new terminology, and there's a reason for that. There is a main axis whose orientation can be changed, which affects the interpretation of other properties you use, but most of the time, you won't change it.
- slipperybeluga 3y ago[flagged]
- justinzollars 3y agoNice intro. I always feel like I'm fighting css.
- nailer 3y agoTLDR: place-items: center;
- primer42 3y agoTldr - it's impossible
- divbzero 3y agoI like the brutally honest cookie notice in one of the examples: We value your privacy data. We use cookies to enhance your browser experience by selling this data to advertisers. This is extremely valuable.
- 4death4 3y agoMaybe I missed it, but position: absolute, left: 50%, transform: translateX(-50%) is usually my go to.
- infensus 3y agoCentering like this can make your element blurry on non-hidpi screens, because transforms are not snapped to the pixel grid like layout properties, and 50% can sometimes land on a subpixel
- 4death4 3y agoIs this still relevant? I thought browsers had proper support for sub-pixels now.
- infensus 3y agoI think this was exclusive to Chrome. https://issues.chromium.org/issues/40431598 https://issues.chromium.org/issues/40431598 Seems like they managed to kinda fix it in some cases, but some of the reproductions provided in the issue tracker are still working, so I would be careful
- wruza 3y agoWhat do you do when position isn’t absolute?
- 4death4 3y agoThen I use one of the approaches listed. However, I find that usually I want absolute positioning when centering either horizontally or vertically.
- hlammers 3y agoI was kinda surprised that this method wasn't included in the article. While I use flexbox for centering most of the time, I still find myself resorting to the absolute positioning way sometimes.
- d_burfoot 3y agoLike many others in this thread, I think CSS is an absolute catastrophe. For me, the key issue is that style directives are constantly either 1) clobbering each other or 2) silently failing to have any effect.
- sodapopcan 3y agoThere are a bunch of comments commenting on other comments so I'm going to join in. These comments are largely talking about how centring is hard from an implementation standpoint and can mean different things. Sure, but the whole "CSS centre meme" is just "How do I put one element dead centre within another". I can't point to data to back this up, but I'm pretty sure that's what 99% of people mean when they ask "Why is centring so hard?" For those of us who grew up with GeoCities and AngelFire etc, the reason not being able to easily do this felt so ridiculous and why it was hard to buy that it's hard to implement is that we were able to do this no problem with HTML, and still can! <table> <tr> <td width="600" height="600" bgcolor="yellow" align="center" valign="middle">hello</td> </tr> </table> That puts the text "hello" squarely in the middle of a 600x600 yellow box [0]. This worked in the 90s. I know nothing about the implementation of CSS, but surely you can understand the annoyance of been handed a new tool, told it's better, yet wasn't able to do such a standard thing lots of people were already doing. It's a big reason I didn't listen to the dogma and kept up with table layouts into the late 2000s. PS, maybe it's Stockholm Syndrome, but I love CSS FWIW. [0] You actually don't even need the `valign` which surprised me, at least not in chromium... I'm not sure if that is a recent thing because I haven't actually written code like that in around 15 years.
- koito17 3y agoWorks in Firefox, too, without the "valign" attribute. Though I would not rely on auto-layout behavior in general since I've always seen subtle differences across the three major browsers whenever using tables without a fixed layout.
- filleduchaos 3y agoYou've been able to do exactly what you describe (i.e. putting "hello" squarely in the middle of a 600x600 yellow box) with CSS since its first incarnation, with e.g. the `valign` HTML attribute corresponding to the `vertical-align` CSS property on an `inline`, `inline-block` or `table-cell` box. But then again, in my experience many of the people who wax poetic about just using tables and/or complain about how CSS is limiting and confusing...never actually put in much of an effort to learn how it works. At least the article's author is self-aware about this.
- wruza 3y agoReasoning about the qualities of a system without having a competing party doesn’t do good in politics (dictatorship), in business (monopoly), in browsers (ie). But it’s different when it comes to layout (css).
- mediumsmart 3y agoGreat article but why would I need a div?
- dingi 3y agoHow come the desktop UI frameworks have this issue solved for decades and CSS/Web still screwing around with mishmash of solutions? I guess, people were afraid to break stuff and kept piling garbage on top of garbage. I think it is safe to assume that the web layout systems suck.
- 5350-uiop-1130 3y agoin css, things seem easy in isolation. it's when you combine styles and inheritance that things get nasty. then add on top: viewports, orientations, layouts, negative margins, collapsing margins, relative positionings ...which can make even "simple" centering into a 6-dimensional puzzle.
- throwaway828 3y agoYou have passed Level 1. Level 2: Put a form and form elements in it. Level 3: Do it with flex.
- eggdaft 3y agoIt’s interesting to note what we can learn from the use of tables for layout. Tables have border, padding, and a cell-based layout arranged in columns. At a stretch they and their cells need white space around them, ie “margins”. Tables are a long established element in layout. And it turns out tables actually contain this wisdom, that all elements should work a bit like table cells: they should follow the box model (fairly obvious to anyone working in typography) but also that they should be arranged in columns (much less obvious and the foundation of grid layout and bootstrap). It’s a natural evolution to come across some layout problems, solve them with tables (as any typesetting system is likely to support tables), and then realise that you need a new facility that has some of the properties of tables but not all of them. CSS has discovered this. Oddly, some systems have not - for example, word processors have not unified elements under a box model etc.
- masfoobar 3y ago+1 Very well done! Clean and to the point - virtual coffee on me! As someone who jumps on-and-off of webdev it can be a little frustrating catching up on latest javascript frameworks and, at lower level, modern Javascript and CSS.
- cubefox 3y agoFor vertical centering, I never understood why you couldn't just give the container a fixed size and then, on the element, set margin-top and margin-bottom to auto. It works like this for horizontal centering. My guess is that the specification treats vertical margins in a weird way. For example, margin-top:50% means 50% of the width, not of the height. I don't know why they decided to do it like that.
- KTibow 3y agoIt's missing <div class="parent"> <div class="child">hi</div> </div> .parent { display: flex; } .child { margin: auto; }
- vietvu 3y agoAfter over 10 years since I started using CSS, nothing changed. Center div still hard.