11 ms·
Absolute Horizontal And Vertical Centering In CSS
- gmjoe 13y agoVertical centering isn't that useful when you already have to know the height of things... I mean, if you already know the heights, you can just put the numbers in straight. The best way to do real vertical-centering that works with variable heights, and doesn't use JavaScript, is to take advantage of the fact that table cells do this with "vertical-align: middle". Inexplicably, only table cells allow true vertical centering with variable heights. So you can either convert the surrounding element to a big ole <table><tr><td></td></tr></table>, or you can use CSS to give it a property of display: table-cell. And in both cases, give it a "vertical-align: middle". Then you're good to go! And of course, horizontal positioning in the table cell is easy.
- ggurgone 13y agoyou can do (real) vertical-centering with display: inline-block too See https://twitter.com/giuseppegurgone/status/388203492365451264 https://twitter.com/giuseppegurgone/status/38820349236545126...
- gmjoe 13y agoVery interesting, I never saw that before! But I can't figure out, for the life of me, why the bizarre ".container:before" declaration is needed -- it would seem to be entirely superfluous, but if you remove it, the whole thing breaks. Can you explain what's going on?
- ggurgone 13y agoHere is a visual explaination: http://dabblet.com/gist/7359467 http://dabblet.com/gist/7359467 The pseudo-element (in red) is 100% tall and both .container:before and content are inline-block with vertical-align: middle;
- tomasien 13y agoThat's not true necessarily: what if you're trying to vertically align something of a known height on something WITHOUT a known height. The thing with the unknown height is responsive, while the overlay is not. That's what I was just doing, found this, fixed my problem!
- MartinCron 13y agoI actually did this just last week, wound up having to use a table cell with valign='middle' and felt both ashamed and proud at the same time.
- jdmitch 13y ago> This will break cross-browser compatibility. That kinda ruined all the excitement for me :( Good of the OP to include all of the alternative techniques that might be better for cross-browser or other specific situations. Seems like transforms are better than the original main suggestion though... why not stick with those?
- pmichaud 13y agoThe fact that this is an interesting article is a huge indictment of CSS. It was developed for a different, simpler use case, and it's obviously the wrong abstraction at this point. Too bad it's entrenched.
- brandonbloom 13y agoI've been saying this of JS/HTML/CSS for years, but people seem to suffer from severe stockholm syndrome.
- morley 13y agoWhat do you suppose we do about it? Like it or not, people use web browsers to access the Internet, and as long as web browsers render HTML and CSS, we have to use the tools we have.
- brandonbloom 13y agoMy complaint is that a lot of people like CSS/HTML/JS. Because they have learned it and gotten comfortable with it. They don't know/understand anything else and their identity and sense of self-worth is challenged if you speak ill of these technologies. That's a big problem. Pragmatically: I suppose that we embrace CSS/HTML/JS as object code. And I mean this in a much more dramatic way than CoffeeScript or SASS. This is finally starting to happen, thanks to browser support for things like source-maps. This is one reason I contribute to ClojureScript! Idealistically: We should be pushing for lower level platforms for code distribution and execution, as well as host platform integration. Portable Native Client and similar efforts shouldn't be so controversial.
- Zikes 13y agoThere have been attempts to fix this by creating languages which compile to each of those: HAML for HTML, CoffeeScript/Dart for JS, SASS/LESS for CSS. The language benefits tend to be fairly obvious, but there hasn't been much of anything in the way of native browser adoption that I've seen yet, apart from Google's plans for Chrome & Dart.
- nerfhammer 13y agoIt's so frustrating that it still requires all sorts of gymnastics to do something so conceptually simple in CSS, and yet many people seem to see CSS as a self-evident imperative to be used in all cases.
- proksoup 13y agoStephen Shaw's (author of the OP article) codepen of the same I sometimes find easier to read, less advertising noise than smashing ... http://codepen.io/shshaw/full/gEiDt http://codepen.io/shshaw/full/gEiDt
- tomasien 13y agoThis is the first time in my life going to HN while I'm futzing with a problem has actually helped. Thought I was going to take my mind off - instead I found the answer immediately!
- recuter 13y agoBefore the inevitable complaints about CSS start flying in, you really actually hate the Box Model and should direct your anger towards it. To wit, the article itself says: "Other Techniques Absolute Centering is a great solution for centering, but there are other methods that may fit more specific needs. The most commonly used or recommended methods are Negative Margins, Transforms, Table-Cell, Inline-Block, and now Flexbox. They are covered more in depth in other articles, so I’ll only cover the basics here." Pray your support matrix allows you to just stick to Flexbox soon and all of this will start to feel like a bad dream from the bygone past. First we abused tables, then we abused divs, now there are actual sane hooks for this, it just took 20 years is all.
- proksoup 13y agoAlso same link was on HN 84 days ago https://news.ycombinator.com/item?id=6214314 https://news.ycombinator.com/item?id=6214314
- ape4 13y agoWhat about using the HTML5 calc() to figure out the center?
- svachalek 13y agoIf you are willing to use something as bleeding-edge as calc, you may as well do it the right way: http://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ http://philipwalton.github.io/solved-by-flexbox/demos/vertic...
- djKianoosh 13y agoOnly that doesn't work in IE10 :( http://caniuse.com/#search=flexbox http://caniuse.com/#search=flexbox
- phelmig 13y agoNext time when I want to explain why HTML/CSS can be a pain, I'll take this example. "Imagine it's 2013 and there is a website that has been online for years, where the greatest hackers and entrepreneurs exchange exciting ideas. When somebody posted an easy solution how to center something in HTML horizontal AND verical it was the favored post on that site for a day" ... ;)
- eeeeaaii 13y agoI personally think it's just incredible that vertical centering in CSS has been so woefully neglected over the 16 years we've had CSS. Every time I read another article about how somebody just maybe has figured out a kludgy way to vertically center things with CSS, I just shake my head. Aren't there any graphic designers on any of the W3C working groups surrounding CSS? Back in the old days when everything was a table-based layout, there was a clean, one-to-one mapping between the grid framework that your graphic designer created and the code underlying the page. Then the semantic web pedants came along and decreed that tables shall never be used for layout. Fine -- but nobody ever bothered to come up with a DIVs+CSS replacement for the grid-based layout that any serious graphic designer uses to build a page. And do you know what happened to the web? Debate cause and effect all you want, but webpage designs are far more boring now than they were 10 years ago. Now it's all just blocks of large-print scrollable text, some images here and there (or maybe a wall of them), and a cute logo. It's like everything is a Geocities page with better fonts and color choices, minus the gifs. I feel like I never see anything really cutting edge or creative in the design space on the web. The internet is a really young medium of course, and it will naturally go through phases, where certain types of design come into fashion while others go out. And I would love it if somebody would prove me wrong by posting some links to some really kick-ass-looking sites. But from where I'm sitting these days, from a design perspective the web is a big yawnfest. Maybe today's websites are more usable and easier to index and work well on a screen reader, but from a graphic design perspective... zzzzz....
- mistercow 13y agoI can't wait until the new version of flex box has widespread support and we can stop relying on these dumb hacks to do the most basic layout operations in CSS.
- Aardwolf 13y agoI'm wondering, why does even CSS3 not have a simple way to vertically center text (or even vertically center anything)? It's a pretty basic and wanted thing afaik... Seems like a higher priority than shadows and 3D effects to me.
- deleted 13y ago[deleted]
- cletus 13y agoThe history of CSS is one where Microsoft earned an awful lot of bad will and what an epic fail the W3C has been in this regard. Microsoft of course deviated from the nascent "standard" such that we've been burdened for years with "if IE ..." blocks to the point that the latest version of IE pretends not to be IE. You reap what you sow. But every time I come across the issue of "how to vertically center in CSS", an issue that has existed for years, I get angry. I get angry because the old way (vertical alignment on table cells) just works. As much as the CSS purists (some might call them "anti-table zealots"), it's hard to argue with something that works all the way back to IE4 and probably beyond (well valign="middle" probably does, CSS vertical-align: middle is probably IE5/6). But beyond this there are so many things in HTML/CSS that should be simple but are hard. This is just one of them. Consider spacing between table cells. There's (still) actually no way to do this... if you want no spacing between the leftmost and rightmost cells and the edge of the table, which I find is a pretty good use case. People end up doing things like: td { margin-right: 0.3em; } td:last { margin-right: 0; } Any such solutions had varying backwards compatibility issues, a problem we're now largely getting behind us, but still... Why can't I specify (separately if need be) the vertical and horizontal spacing between cells separately to the edge of the table (which should really be a property of the table rather than the cells IMHO). The problem here is that the CSS WG seems to have started with a model and then just run with it without running it through very common use cases. Looking at the article, it looks fine. One thing I'll say is it starts off with the "margin: 0 auto" trick, which everyone who does anything with CSS needs to know. Why is centering that hard? Why can't I just say "put this in the center"? Why can't I then use margins to offset from center or something? Also FWIW, the margin: 0 auto thing didn't work in older versions of IE if you didn't specify a DOCTYPE and force "standards compatibility mode" (rather than the euphemistic "backwards compatibility mode".
- camerondaigle 13y agoGood grief, if the element to be centered has a fixed height and width, then there's nothing to this. I've been using the negative margin method for years: http://jsfiddle.net/mBBJM/2155/ http://jsfiddle.net/mBBJM/2155/ Not that it's any less Stockholm-Syndrome-y than the linked article's solution, but still, I have no clue why this is on the front page of HN.
- Segmentation 13y agoFront-end stuff always seems to make the front page of Hacker News. I think it's because front-end is easier, and possibly more "hip" right now (as far as jobs go), so there's more interest in it.
- nostrademons 13y agoI'm a full-stack engineer that started out on the front end. I don't think frontend is easier - in terms of the amount of background you need to know to produce something useful, being a frontend engineer is significantly harder than being a backend one. However, frontend stuff demoes better. If you do a fancy machine-learning analysis of some public data set but present it as a command-line app or a table on some bare-bones website, people will be like "Uh, what's the deal?" If you make things fly around the screen in cool patterns, they'll be like "Woah! I didn't know you could do that!" A lot of this is also because a frontend engineer's job is to lower the cognitive processing a user has to do, while a backend engineer's job is to come up with useful things to cognitively process. In other words, when a backend engineer comes up with a demo, they make the viewer work to understand it, while when a frontend engineer does the same they make the viewer go "Ooh! Aah!"
- camerondaigle 13y agoFair enough. This seems like CSS Positioning 201 to me, but I've been dealing with this stuff for a long time now, so my perspective is probably pretty skewed. I completely agree with your point re: cognitive processing: good CSS communicates intent to the reader, so if this kind of stuff is unclear to people and the Smashing Mag post helps the concept click in readers' minds, then it's a win :)
- ffrryuu 13y agoCSS grid is the future.
- pete_b 13y agoThere are, in-fact, and have been for a while several known ways do do this in CSS 2.1 this just being another with a similar long list of restrictions and context requirements. http://css-tricks.com/centering-in-the-unknown/ http://css-tricks.com/centering-in-the-unknown/ They're all much of a muchness, at least we'll be able to just use flexbox soon enough.
- aschearer 13y agoI'm curious why there isn't something like TypeScript or Coffeescript for CSS? I'm aware of LESS and SASS but to my knowledge they don't go as far as their JavaScript complements in adding future-looking functionality. Is it simply not possible to add CSS grid or flexbox (or both!) support to LESS and have it compile down to plain ol' CSS?
- swordfish0321 13y agoNot sure what you mean by "future-looking functionality". I don't know anything about TypeScript but CoffeeScript is just an opinionated way to generate JavaScript. Isn't that what both LESS and SASS do for CSS? Regarding grid or flexbox, that is ultimately a design decision/preference of the architect. So using your example, if SASS inherently used grid that would be like CoffeeScript introducing MVC into your project.
- aschearer 13y agoTypeScript adds some features planned for Javascript such as classes with inheritance and modules. The thinking is that when these features become standardized your TypeScript code will be valid Javascript. (Or at least as far as those features are concerned.) So in the same vein, why doesn't SASS provide the next generation of CSS functionality? That is, you use the proposed syntax for CSS grids and it transforms that into whatever mess is necessary to emulate it in today's CSS. Later when CSS grid support is available no translation is necessary. I suppose the answer is because it can't do so in CSS alone and that emulating CSS Grid would require CSS, DOM, and Javascript to be emitted from the compiled SASS script. It would be neat if someone who knew more could confirm my suspicion. I'm not sure I follow your example regarding CoffeeScript and MVC.