Hacker News new | comments | show | ask | jobs | submit login
CSS Grid for UI Layouts (hacks.mozilla.org)
455 points by jhatax 6 months ago | hide | past | web | favorite | 104 comments



The biggest win I've noticed from CSS Grid so far has been from `grid-template-areas`. (The `grid-column` and `grid-row` syntax used in the article is kind of an alternate way to spell this, but I prefer using the `area` properties.)

Ever been given mockups where the mobile design moves stuff all around into a different order? That has traditionally been extremely difficult to handle with CSS given identical, unchanging markup.

With CSS Grid you just give each of your components a `grid-area` name, and then you just tell the grid where those areas go at different breakpoints.

So on mobile you might have 4 components laid out in a single column:

    grid-template-areas:
      'breadcrumbs'
      'filters'
      'sort'
      'products';
And using a @media query, a more traditional desktop layout (and add a `categories` area):

    grid-template-areas:
      'breadcrumbs breadcrumbs  sort'
      'categories  products products'
      'filters     products products'
      '.           products products';
I love it because not only is the above a list of the subcomponents that make up this component, but it's also a visual indicator of how they'll be laid out.

Now all the subcomponents need to do is define their `grid-area`, they don't need to adjust their own layout at the different breakpoints.


Using this part of the CSS Grid syntax, I made a responsive Brady Bunch demo. Disclaimer: the theme song will autoplay on desktop. https://codepen.io/antibland/pen/VMzxqm


I'm very sorry as I know "+1" type posts are bad, but that is my favorite disclaimer I've ever seen.

Any recommendations from either of you on material on grid-template-areas? It sounds like it would be great for getting away from the hack of having a mobile menu and a desktop menu on our existing site (with the one for that format rendering and the other hidden), which I've hated as it is a pretty clear indicator I couldn't find something more appropriate.


I came across them from this video, when I heard the "it's almost like ASCII" part (I had it on in the background) something clicked in my head and I had to drop everything to try it out.

https://youtu.be/7kVeCqQCxlk?t=1039

Watch on for the 'crazy response design' part.

I am still amazed.


Thanks for that. At work, they push site should look the same across all browsers very heavily (well, desktop = desktop, tablet = tablet, mobile = mobile). I’m going to try and share this video with one of the guys that dictates design a bit and see if I can convince to get away from all of the hacks built into it that end up breaking little edge cases which then requires browser specific hacks. It’s a longshot, but he likes bleeding edge so fingers crossed.

This is incredibly compelling stuff though. First thing in a while I’ve seen that has left me floored.


So I found MDN's documentation on it (https://developer.mozilla.org/en-US/docs/Web/CSS/grid-templa...), but wasn't 100% certain on how the implementation works. Namely, how footer and foot were related.

At first I was thinking it was inferring first HTML element seen (head) relates to first area element written (also head), second HTML element seen (nav) and second distinct area element written (also nav), and third HTML element (footer) with third distinct area element written (foot). Then I see the pretty obvious grid-area within the CSS handling that linking and I must say, that's beautiful stuff.


I'm a little confused because in your example, grid-template-areas lists words that are the same as the class names on the elements, but I'm not (yet) sure that grid-template-areas takes a list of class names rather than them being arbitrary identifiers for the areas being laid out.


The class names don't matter. Each grid-template-areas value has to match the grid-area value (the actual grid item being placed).


Right, but do you see how you've used the same terms for both?


I see. I only added the class names to provide a container for each child to point to where it should be placed. The fact that I named the class and the grid area indentically could seem a bit confusing. Something like "marsha-container" might have been clearer.


The song, thankfully, did not autoplay on my desktop. But then again, my daily browser nowadays is Safari on MacOS.

Looks like Chrome does autoplay, so does Firefox.

I'm kinda liking how Safari handles privacy, tracker blocking, and autoplay blocking.


autoplay can be disabled in Firefox with a simple configuration tweak, and I'm sure it can be in Chrome as well.


Thinking about how difficult this must have been to do with 1960s analog video technology makes this feature more impressive.


Woah, I didn't fully understand how that works given the OPs description, but after seeing it in action... that's amazing!


Fantastic comment: useful, succinct, instructive.

>"I love it because not only is the above a list of the subcomponents that make up this component, but it's also a visual indicator of how they'll be laid out."

Yes! Love it.

Tangent: This reminds me of some native iOS layout thing from maybe 6 or 7 years ago but I can't recall much about it-- scratch that, googled and, yeah, "VFL": > "The Auto Layout Visual Format Language (VFL) allows you to define constraints by using an ASCII-art formatted string."

IOW, ASCII art for layout implementation.


combine this with rem sizing units for font and padding -- now you're playing with power


How about ch units? Heard someone mention it recently and am curious if people are using it. There is often a need to confine a layout to a certain amount of characters and it seems that this unit is better than rem/em for those cases. I would think there's a way to combine em, rem and ch to make some robust layouts.


Also, size your root element font using vw or vh. Then things become really responsive when done right.


Please don't do this. Just because I've got a large viewport, it doesn't mean I want massive text, and just because I've got a small viewport, it doesn't mean I want tiny text. Either extreme can result in very frustrating to read and potentially inaccessible text. Perhaps it makes sense in some narrow cases (e.g. the main page title), but certainly not for your body copy.


With calc() you can get some pretty decent scaling based on vw. If it was just a direct proportion of vw, then yes, things may look a bit on the larger side on a bigger screen, but as with a lot of things, if used with care, the results are pretty nice.


It's not something that would be done as the only thing that influences the final fonts size. As another comment pointed out, it could be combined with calc(). But also, within media queries, to achieve reasonable results in various widths while still responding in a subtle way to the actual viewport with of the client.


Not only power. It's a nice trick for non-designers to create nice looking designs. But you have to keep in mind to use only 2 or 3 sizes of padding and margin. For example: 0.25rem, 0.5rem and 1 rem.


The strangest phenomenon I have encountered when using Flexbox and Grid in CSS is a nagging sense of guilt. Through two decades of web development, my brain has so absorbed the idea that easy CSS layout is only possible through non-standard, browser-specific CSS or "wrong" things like table-based layout that it just won't accept that it's no longer the case. It's like when you leave school, but for years you still have dreams you're late for class.


I have this recurring dream that I'm late for a final exam. Long term memory can be evil sometimes.


I can justify your guilt. There are still many browsers and many users using them that do not support CSS Grid. It's a cutting edge feature. Please don't force us to mobile sites (I'm looking at you Mozilla/FF extension site) or just fail to have a fallback entirely.


87% globally seems pretty good. Those without it now probably won't ever get it.


How CSS Grid is non standard? It's defined by W3C: https://www.w3.org/TR/css-grid-1/


You misunderstood. They meant that CSS Grid is easy and that for many years things that have been Standards Compliant weren't easy, so it's a bit of a hurdle to let go of the "if it's easy, then it's probably a non-standard workaround"-mindset.


10 years from now:

The fundamental problem with CSS Grid is that it is two dimensional. This makes CSS Grid great for two dimensional uses, like aligning content both horizontally and vertically, but it begins to fail when I need to align content with the user's hand. Instead I need real three dimensional layout, which is why I need CSS Matrix. Fundamentally Matrix is 3D.


Mathematicians will have generalized CSS into arbitrary dimensions long before CSS grid is widely adopted.


I feel like I could use a 3d layout tool today to escape the z-index dance that seems to be in every code base I've worked in. I'm forever bumping z-indexes like it's an arms race or something.


All you need to do is add float to CSS Grid ;)

https://news.ycombinator.com/item?id=16307116


CSS Tensors.

You heard it here first.


CSS Specificity Fields. In addition to the standard algorithm for specificity of a rule, you will be able to define a function that gives the specificity at any point in N dimensions. Rule priority at any point will be determined by relative field strength of the competing rules at that point.


CSS Lambda Calculus


Do CSS properties accept quaternions?


>> Also note that CSS Grid does not deprecate Flexbox

I see this said a lot but in my experience (a) all the cases where I use flexbox eventually get replaced with grid with about the same verbosity but more flexibility and (b) I've noticed subtle bugs when using flexbox with grid that manifest only on some platforms (e.g. On iOS but not on Android, only on some versions, etc).


CSS grid is strict rows+columns, flexbox is 1-dimensional and allows for controlled wrapping to a second/third/etc row when the row (or column, depending on orientation) is filled.

They have different use cases, it's just that (at least with regards to (a)) everyone's switching because they wanted something like grid in the first place and only had/knew about flexbox. It got you halfway there (we've used multiple flexbox rows that don't wrap to simulate grid, for example), and now they're just going all the way.


I think the parent new all this and was saying that when using flexbox with grid, each for their intended purpos, there are bugs in various browsers for them.


jQuery in three lines. Awesome.

  const $ = (selector) => document.querySelector(selector)
  const $$ = (selector) => document.querySelectorAll(selector)
  const on = (elem, type, listener) => elem.addEventListener(type,listener)


While I understand your sentiment, jQuery was never just about selecting elements in a simple manner — it took care of countless browser bugs and inconsistencies for you, which is why it became as popular as it did. Not to mention the large plugin ecosystem, which you may have loved or hated, depending on your preference.


  const $ = document.querySelector
  const $$ = document.querySelectorAll
:)


thats illegal invocation

```` $ = document.querySelector.bind(document) ````


you need to .bind(document) as querySelector aparently acesses its parent object (or use @bind or related : syntax when it's released)


Even better


Here's a good video with Rachel Andrew: "Into the weeds of CSS layout". It goes into detail how the browser calculates the layout / sizing.

https://youtu.be/BIeJNFDXyMI


I shall never begin to grasp why Grid was not a top priority and feature in CSS 1.0.

Two+ decades spent on kludges to have things line up in columns.


Because when CSS 1.0 was being designed, the primary use case was documents, not application interfaces. The processing model revolved around streams of content flowing downwards, with the occasional exception.

That's why laying things out vertically with CSS is often more challenging than laying things out horizontally. The assumption was that content starts at the top and flows downwards on an infinite canvas until it is finished, with the length of the document defined by the content. Contrast that with the width, where it has a finite size defined by the viewport and is wrapped.

This processing model makes perfect sense for documents, less so for application interfaces.


Yes, I know that rationale.

But please! CSS was a web technology from the start. I routinely committed the deadly sin of table layouts from the mid nineties all the way up into the new millenium, because that was the only way to do it. It is utterly beyond me how CSS - glib explanations or not - could blithely ignore this very real need all through 1.0, 2.0, and well into 3.0.

But I must say, Grid was almost worth the twenty years wait, and it does bring on a sweet nostalgic rush once again having to shake a fist at various MS browsers.


> CSS was a web technology from the start.

Sure, of course it was. But the web was almost entirely a collection of documents back then.


Not how I remember it at all.

By some felicitous fluke I still have the very first html I ever coded, anno 1995, complete with background sound and animated gif - but cut me a bit of slack: It was purely a personal excercise. The thing was done purely from what I'd learned studying source of available websites. The point being: My God, it's full of tables. They were a real thing by that time.


PDF documents have tables. Documents are things meant for a human, it's not raw data, for computers to understand it you need machine learning.

Applications are not based off documents but rather the raw data (which the machine natively understands).

The transition of web from documents to a dumb platform for application software delivery is why the web is no longer the web. It is just application delivery infrastructure now. Each application lives in a walled garden and is no longer a "web" at all.



You are being downvoted, but are asking the right questions.

I learned the fundamentals of graphic design through print design, as that is a medium that designers have worked with for much longer than the computer screen. A lot of designers approach print design by starting with a grid that describes how their content will be laid out, and proceed from there. Of course, you can find exceptions to this (although in many cases they will be an example of a designer breaking the rules because they know them so well), but most design students will be familiar with that approach.

"Grid Systems in Graphic Design" (1981) is one of the reference texts on this subject, if you're interested in getting deeper.

The other commenters say, in reply to your question, that it was just for formatting HTML, and for web documents rather than applications. That is just completely missing the point - print documents are documents too, not applications. The main argument that the web is so different from print because the canvas is infinite doesn't make much sense either - even if the canvas is conceptually infinite, it still renders on a finite surface (your screen), and one can design modular grid systems that easily accommodate that (as well as the other related concerns, like the user not having the right font installed, or different pixel densities/aspect ratios, etc.).

In the end, the best explanation seems to be that the CSS spec was never led by actual designers who could envision the sort of problems that one would face when designing documents for the web. The CSS spec committee is full of very hard working, smart people, but they have the concerns of engineers first - browser compatibility, rendering complexity, etc. - rather than designers.

The fact that the "holy grail of web design"[0] is a thing is absolutely mind blowing to me. This is the kind of design any first semester design student would execute, and any styling language that does not let you implement it in 10 lines is a styling language resolutely not designed by (or for) designers.

[0] https://en.wikipedia.org/wiki/Holy_grail_(web_design)


Even considering that those working on the specs were fundamentally engineers who didn't think in grids like print designers, it took an awful lot of ignoring how people were actually implementing commercial websites in the late 1990s to leave grid layouts out of early CSS specs.


I wish I could upvote this multiple times.


Here's the history of CSS layouts as told by a CSSWG spec writer: http://fantasai.inkedblade.net/weblog/2012/css-layout-evolut...


Neat writeup, thank you.


The goal of CSS 1.0 was to just move formatting out of HTML; it added relatively little beyond what was already doable with HTML (and a lot of what was new were things needed to typeset howcome's PhD thesis nicely).


Goddamit, this actually makes sense. Guess I need to learn CSS grids now- Yet another task to fill up my already overflowing todos.



that's really nice. Looking at level 3, why is -start inclusive but -end exclusive? start = 1, so it isn't zero-based, that I get, but if it starts with 1, it looks like it would end with 3, but 4 is the answer (1 and 3 only sets the first two columns).

I get that that is CSS, not the game's rules, so not arguing why the game handles that way, I'm just curious what the motivation is for the CSS rule.


When you use numbers, it's referencing the lines between sections, not the sections themselves. So a grid of 4 columns will have 5 line numbers.


I found this a strange decision in the Grid standard design. Surely most people* would think more in terms of "cells" that "cell-dividing-lines". Then again, compared to the design decisions in much of the rest of CSS including every other standard layout mechanism this is a fairly small gripe, overall CSS Grid is a big improvement. And when using the excellent "grid-template-areas" (compared to ASCII art elsewhere in this thread) you don't really specify start and end points anyway.

* By people, I mean designers (used to bootstrap-style grids), coders (used to arrays) and everyone else (used to spreadsheets).


But in this case you have 1,2,3,4,5 and start 1 end 4 selects 1,2,3. So it appears inclusive 1, exclusive on the 4 to me. If it were like some instances of substring where it is (index, count), I could get that, but it almost reads as "start right here, end right before this."

Actually, wait. Thought on your line numbers a bit and I'm thinking that points to each vertical line as a number (so in this garden's case, 6 per row). I just plugged it in as that and it follows. Just feels foreign to me as I'd do start/end 1 for just first cell, start 1 end 2 first two cells, etc. I'll get accustomed to it though. I wonder if there are other scenarios that followed the same logic in CSS that I just didn't attempt to really grok. Thanks for pointing it out.


This is a great tutorial but it will give you zero hints if you get stuck.


Cutest thing ever.


Does anyone here have experience using CSS Grid on IE? I would like to start using it, but at work we have to support IE11, and I understand that it implements a different version of the standard. Is the amount of effort required to support both versions worth it?


It's not as simple as using auto-prefixer, since IE10 and IE11 use the older syntax. However, it's surprisingly not that bad for simple layouts.

Here's a great resource covering the hows and whys: https://rachelandrew.co.uk/archives/2016/11/26/should-i-try-...

And here's a simplified example I threw together recently to demonstrate it in action: https://codepen.io/shahab/pen/ypWmZG

Basically, you lose auto-placement, named grid areas, and simple grid gaps, so you have to manually place items in the specific row/column for IE. But, I've found that it's still easier than the alternative in many cases.


Autoprefixer should take care of this for you. You write standard grid layout and it works on IE11.


This is not true. IE11 simply doesn't support the whole of CSS Grid, and tools like Autoprefixer don't and can't add support.

If you limit yourself to only using the parts of CSS Grid that IE11 supports, then you can write the standard equivalent to that subset and Autoprefixer will translate it for you, but you can't "just write standard grid layout", because that includes things there is no IE11 equivalent for.


Autoprefixer doesn't take care of this for you. You either write a bunch of -ms properties, or get your preprocessor to do it for you. Here's a working example: https://codepen.io/ksenzee/pen/OzRejj


My understanding is that the MS properties don't map 1-to-1 onto the standard CSS properties, so I don't think this would always work, hence the question. That said, I assumed Autoprefixer didn't support CSS Grid for that reason, so thanks for pointing out that it does.


Autoprefixer doesn't just add prefixes, it translates the the syntax to browser compatible code as well, for example:

    a {
        display: flex;
    }
Translates to:

    a {
       display: -webkit-box;
       display: -webkit-flex;
       display: -ms-flexbox;
       display: flex;
    }
It supports the 27 differences between the various browsers.


Given CSS Grid, what role do frameworks such as Bootstrap play?


Understanding where to put a bunch of class names is a lot easier than understanding CSS. Bootstrap isn't really about working around CSS, often it's about avoiding it. CSS Grids will likely just make Bootstrap easier to use, maintain and extend.

I personally stopped using Bootstrap years ago when I gained a good understanding of CSS. The most common features that Bootstrap provides (components and layouts) are not hard to implement yourself. And you'll avoid littering your markup with brittle combinations of class names and nested <div>s.


Such framework are abstraction + stylized components. They will continue to fill the same role.

I can tell my client's IT guy "just put a div with a class of .card and then a div with class .card-body in your WYSIWYG and you will have the correct display".

That the framework use floats or flex or css grid is irrelevant to the end poweruser.


A certain frsction of Hacker News commenters have declared Bootstrap useless and advocated just writing your own custom CSS from scratch since before Grid, and before Flexbox and before supporting IE 7 could safely be ignored so bear that in mind when evaluating the answers you receive.


I prefer making the template myself, but coding from scratch is not for everyone. Bootstrap is useful then depending on project, and what you can tolerate in terms of code bloat and bag of tricks bloat.

I pass the template I make along to the next project, and improve the template as I go. By using frameworks you're hand-balling the task of "making it better" to someone else. As for css grid, not using it yet due to my wanting to support older browsers, but I am now enjoying flexbox for page structure after ignoring it for a long time. Flexbox is a great set of tricks.


"By using frameworks you're hand-balling the task of "making it better" to someone else"

You sound a bit ambivalent about whether this is a good thing or not.

I would guess most hand-rolled alternatives don't have a long list of well documented browser bugs they couldn't work around and don't have half the workarounds for things they could handle. Instead they'll just silently break since they don't have the QA exposure across obscure platforms that Bootstrap does as a massively popular open source project:

https://getbootstrap.com/docs/4.0/browser-bugs/

I would guess Grid has just as many issues, and would guess that Bootstrap will adopt it at roughly the time it becomes supported by a wide range of browsers, and will have implemented and tested workarounds for any lingering issues with it.

Bootstrap seems to tickle the same "I could write Dropbox over a weekend" response that Hacker News commenters are famous for, just from those with a slightly different technical skill set.


Until Bootstrap adopts CSS Grid (v5?) I'd love to hear stories about folks using CSS Grid and Bootstrap components/typography/styling (i.e. everything other than Bootstrap's grid) together.


My opinion is that CSS bloat is way more harmful than bloat in any other language. I do indeed prefer to start from a blank state every time, or take a small template and eagerly cut everything that is not immediately useful out of it.

That said, I see the value of a CSS "library" for a large team that has to agree on both a template and terminology.


Maybe some cool defaults? Colors, buttons, typography etc.


UI elements still need styling and normalizing. Grid is just one of many UI components in Bootstrap and similar frameworks. I imagine Bootstrap will put a layer of CSS class abstractions on top of CSS Grid to make it easier to work with, just as they did with flexbox.


I think Flexbox already removed the need for a CSS framework. Kind of the same situation as when improved DOM APIs (and browser compatibility) removed the need for jQuery.


Productivity. Bootstrap class names are still simpler than css and allow something to just stay within html. Also standardized themes and components allow for quick development compared to doing it all yourself.


I see component libraries filling in the gaps for css grid and flexbox. Get rid of the jquery dependancies, but imo ideos bootstrap 4 and others.


can anyone think of a situation where flexbox > css grid? (apart from compatibility). On a similar note, is there any use case where float is still best?


Float might still be the best option for its original design intent: word processor style documents where images are placed within text flows. In other words, something like a blog post's content (but not the UI chrome).


Flexbox: distributing a variable number of elements, like an image gallery.

Float: in sections where there could be a variable number of columns, and the columns could have variable possible widths, using floats can be simpler than grids.

This is because you have to maintain many different grids (and their media queries) for the parent display:grid elements, and with floats you're only styling child elements.


I'm not sure I follow your second example. I might need more detail to understand how grid-auto-columns (https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-c...) does not meet this use case? It's possible I haven't been in the weeds enough on grid yet.


I love CSS Grids, finally a bit of native layouts sanity on web development (flexbox still wasn't quite it).


I look at the usage data of our website and see so many IE 11 connections and I sigh.


How different is the older specification it supports? Also it's prefixed, so it could in theory be specified without disturbing newer browsers.


Cool, so I can do what I've been doing with WinForms TableLayouts since forever /s


You have never been able to do what CSS grid can with table layouts, or any other layouts. Grid allows you to freely position your content anywhere on the grid regardless of the content position in the HTML, which was not at all possible with the tables and was limited with floats/other layout techniques. I do not count position: absolute, because that's brittle as hell.


I find it hilarious that after all these years we are back at working with grids.


Grids are one of the best tools in creating interfaces. Yes, there are many UI's that don't use grid layouts, but for the many, many that do CSS Grid is a great tool.

Did you mean HTML table based layouts? Because yes, it's good those days are behind us...


I find grids too complex to be useful, and their applications are very limited. Now that we have flexbox we can use that to create any sort of layout that's also very responsive and scales well on all sorts of devices. The grid seems kind of redundant. Off the top of my head, I can't think of a scenario where it would be useful that a flexbox won't cover. It's great that we don't have to shove floats everywhere where they don't belong though.


Did you read the article? It's kind of about exactly why that's not the case.


The problems the author has still can be solved with a flexbox, it's just that a grid offers an alternative. There are justify-content and align-items properties that with a properly designed nested arrangement of flexboxes can help to create any layout that a grid can create.


Template areas make responsive designs trivial. You just redeclare them for desired viewport sizes and that's it. Also grid gives you more independence with regard to content position in the source.


Yeah, but you need to create container elements to make it happen, cluttering your HTML and making it more difficult to swap elements around the grid as needed.


That's true, although I wouldn't call containers "clutter", they have multiple uses. But yes, flexbox though easy and logical, still requires messing around if you need to reposition or change the configuration of things. It's not awful but probably slower than css grid. For me, I don't usually need to switch things around too much with layout, I sort that out before build.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: