
CSS Grid for UI Layouts - jhatax
https://hacks.mozilla.org/2018/02/css-grid-for-ui-layouts/
======
exogen
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.

~~~
antibland
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](https://codepen.io/antibland/pen/VMzxqm)

~~~
jsgo
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.

~~~
benjaminjackman
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](https://youtu.be/7kVeCqQCxlk?t=1039)

Watch on for the 'crazy response design' part.

I am still amazed.

~~~
jsgo
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.

------
stupidcar
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.

~~~
superkuh
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.

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

------
deckar01
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.

~~~
dredmorbius
CSS Tensors.

You heard it here first.

~~~
SiVal
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.

~~~
dredmorbius
CSS Lambda Calculus

------
mephitix
>> 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).

~~~
Izkata
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.

~~~
themarkn
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.

------
thibautg
jQuery in three lines. Awesome.

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

~~~
Felk

      const $ = document.querySelector
      const $$ = document.querySelectorAll
    

:)

~~~
dpweb
thats illegal invocation

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

------
Teichopsia
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](https://youtu.be/BIeJNFDXyMI)

------
interfixus
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.

~~~
GuiA
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)](https://en.wikipedia.org/wiki/Holy_grail_\(web_design\))

~~~
notahacker
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.

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

~~~
stctgion
[http://cssgridgarden.com/](http://cssgridgarden.com/)

~~~
jsgo
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.

~~~
xweb
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.

~~~
fineline
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).

------
RussianCow
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?

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

~~~
RussianCow
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.

~~~
dmix
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.

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

~~~
ZeroGravitas
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.

~~~
exodust
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.

~~~
ZeroGravitas
_" 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/](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.

~~~
jimmcslim
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.

------
darepublic
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?

~~~
ino
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.

~~~
themarkn
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...](https://developer.mozilla.org/en-
US/docs/Web/CSS/grid-auto-columns)) does not meet this use case? It's possible
I haven't been in the weeds enough on grid yet.

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

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

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

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

~~~
rimliu
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.

------
nukeop
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.

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

~~~
nukeop
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.

~~~
function_seven
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.

~~~
exodust
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.

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

~~~
knowingathing
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...

