I haven't been able to grasp either grid or flexbox. The last layout strategy I was decent at was floats. This article made me feel confident to use a css grid next time I am designing a layout. Well made! Thank you.
Probably a cliché question at this point but
isn't all of this solved more easily via flexbox?
Flexbox -> 1-dimensional layouts
Grid -> 2-dimensional layouts
That being said, I use Flexbox for pretty much everything.
For me its:
Flexbox -> Content first, Layout second.
Grid -> Layout first, Content second.
That‘s a very popular over-simplification. A better one would be:
Flexbox -> the children define the size Grid -> the parent is in control
Kevin Powell has a few great videos on YT comparing flexbox to grid. Grid can be very powerful if you want overlapping grid areas. Something that was previously only possible using absolute positioning. Also, auto-fit and auto-fill
not at all, the wet dream of css is to be able to layout just with css and only semantic markup, to which flexbox falls short sometimes because you need to add non-semantic elements (columns and rows).
The main reason I tend to reach for grid is responsiveness. Makes it way easier to change the layout at different screen sizes.
One thing flex cannot do well is white space: how do you leave a gap of content without spacer divs?
This becomes more complicated when the number of divs is dynamic as flex determines position based on siblings. With grid you already have defined the “layout”, and you are just placing the div into the correct position.
Grid does that in both axis too. So although you may be able to kind of replicate the 1d version with flex, it becomes much harder to align in 2D.
I wrote an article about this: https://cssprinciples.com/3/grid/
I typically look at grid as the outermost container. It is very good at dealing with coarse layout concerns because you can constrain on both dimensions and define a layout per media query (or whatever).
I've never been in a situation where nesting grids makes sense. Nesting flexbox obviates the need for grid in most cases.
Wait, '1/3' isn't a fraction, it's a range from 1 to 3? Why in God's name would they choose that syntax? Ranges have plenty of reasonable, well known syntaxes in programming. E.g. 1..3
The very first thing you need to know about CSS is that it uses the language of print layout, not programming.
A lot of the problems programmers seem to have with CSS probably stem from this misapprehension.
Do you have a reference for this particular usage of slash? In print, “x / y” is often used to mean “item x out of y” [0], for example in page numbers. I’m only familiar with using slashes for ranges in ISO 8601, where it has purely syntactic reasons and (AFAICT) doesn’t adopt any preexisting convention.
I imagine the slash in CSS grid is for similar syntactic reasons, because the syntax also admits hyphenated identifiers [1] (custom-ident), which precludes the use of “-”. (They could have used a range operator like “~” or “..” though.)
[0] https://en.wikipedia.org/wiki/Slash_(punctuation)#Numbering
[1] https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column...
And that is exactly what 1/3 means in CSS Grids, the element occupies the grid from slot 1 to 3.
“1 of 3” is not the same thing as “1 to 3”, so I don’t think they mean the same thing here.
As far as I know, 1/3 means "one of three" in print - which actually is division ("1 of 3" means the subject's position is 1/3 of the way through).
CSS uses "/" for division (fractions) inside `calc`, so I don't think not understanding the language of "print" is where the frustration comes from nowadays. I think CSS is also part programming language now.
Imagine telling a programmer that in CSS - !important means "important!", not "not important" :-)
While I like grid functionality, the syntax is really different from lot of other CSS, and it's confusing imho. It's like this corner where you can see they either developed it in isolation or felt they were "going to do it right this time" or something.
while I love CSS Grid and Areas I still think the hardest part is managing responsiveness especially between mobile and desktop sizes. I find that grid-template-area and the rows / columns sizes needs to be updated via JavaScript based on what UI elements should be open / full screen
I haven’t found a world where minmax or calc fixes this. hope someone has answers!
I was surprised to not see the author call out how amazing template areas are for responsiveness. Using media queries lets you define different grid areas for different screens and then your elements can be moved to whatever layout you'd like for that screen size. If you need to hide an element at a certain size just give it display: none at that size.
Here's a very simple example: https://codepen.io/trescenzi/pen/vYqpjvL.
The author shows media query examples like that in 6.2 and 6.4.
But I thought that using screen size media queries is an anti-pattern, and that we should be aiming for fluid design without arbitrary breakpoints.
That’s how I understood it too and it works. But the navtoggle and maybe asides need the width trigger it seems. I want to learn named areas in grid and just use that. Going to read the article and do that.
Have you tried media queries?
I have zero clue why this is downvoted. You can combine media queries and grid template areas to obtain arbitrary cross platform layouts without a single line of javascript.
I believe that many such cases can be solved by using :had() and/or subgrids, but I do not have too much experience in this
The way to go with this is to still use a grid, but make the row/col values be css variables ( "var(--foo)" ) instead of fixed values.
Then you can update the value of just that variable from JS, and the grid will reflect it.
I was very intrigued by the animated demos, but apparently the animation is not accomplished with CSS :(
I definitely learned flexbox and thought to myself "this is good enough", and haven't really pushed myself to learn grids. It does seem like there's some reason to prefer grid [0], but it overall I've never needed to do anything that can only be done with grid (except data tables, for which I use actual tables).
That's great that you've learned a tool that covers all your needs.
I've only used grid for responsive image galleries like https://labs.jensimmons.com/2016/examples/image-gallery-grid... or responsive cards like https://every-layout.dev/demos/grid-cards/. `grid-template-columns` is good to learn. `grid-gap` is convenient. Flexbox seems to handle everything else.
But I'm still iffy about grid template areas. The article makes a case for easily adjusting layouts per breakpoint, or "for team members who might need to change a layout." Maybe I'm just not the target audience.
If you can target (somewhat) modern browsers, then you can also use `gap` with Flexbox. Works great!
https://caniuse.com/mdn-css_properties_gap (no IE 11 support)
Grid template areas is very similar to traditional print layouts that are constrained with both a width and height. If you need something like grid-auto rows it is less useful.
But what’s nice about it is that, if you want them, grid areas are extremely declarative. With non-area templating, you are defining the layout based on the items, and that can be challenging.
Flex is good enough for most things, but grid has its place. Responsive grids (think of those 3 column card layouts that shrink to a single card per row layout on small screens), page layouts like dedicated sidebar areas, resizable elements that should stick to a certain layout despite the resize, etc.
Nothing stopping you from using both as necessary, combined it's a very strong layout tool
"No, Flexbox isn't "good enough" https://www.youtube.com/watch?v=MWWcZzossc8
A fun tool for grid learning: https://cssgridgarden.com/
things like justify-content, align-content, align-items, align-self confuse me, they change based on block and inline settings and the naming is also too indistinct. in the end i just find it frustrating.
sometimes miss the days of table layouts.
i think flex and grid are fine if you stick to the basics. but when you start having nested elements and things like display: content. things can become unmanageable.
In Chrome DevTools, I just enter the required value (center/end) and scroll through the suggested properties until the desired effect is achieved. No need to remember them.
This is exactly how I do it too but I'm not too proud about it. I can propose index changes in a postgres db and explain the reason behind performance improvements but I can't remember the CSS properties that'd put my content in the correct boxes.
You can also click on the little “flex” icon next to the display: flex property and bring up a ui that has all the flex properties (if, like me you can’t remember what property does what)
The naming is super annoying, but for Grid it is least a consistent mapping:
- align-* is inline axis.
- justify-* is block axis.
- *-content is aligning grid tracks (rows/columns).
- *-items is aligning individual children within their grid area.
i find it hard to remember that.
I hope that's not a stupid question, but why define the syntax as 1/2 and 3/4 (divider) and not 1-2 (column 1 _to_ column 2) and 3-4 or 1->2 or something like that?
The column number can be negative. 1--1 vs 1->-1 vs 1/-1 ?
a:b is almost universal as a range designator at this point. / is a _terrible_ choice, especially in a context where a fractional value would also make sense.
That was just an objectively bad syntax choice, but probably keeping on track with CSS.
Don't you think : is already used for something else in CSS?
making excuse is easy, here is another one 1..3
And what’s wrong with whitespace? Like every other property.
Oh my God. What we have done ?
We've handed visual layout markup to a bunch of software engineers who don't then consider that this should not be an engineering "language" when adding new features, which pushes closer to the hands of day to day engineers who then try and solve problems that shouldn't exist like portability and reusability. So we end up with a mishmash of nonsense that is neither simple enough for the intended user case nor smart enough to be able to be shifted to a higher level of engineering skill.
Fixed CSS layout?
Is there a pre-intro version of this document? I am lost at the Introduction itself and not able to get past it. In particular:
If I need to position child items within the grid, I need to specify the line number for each item by using grid-column.
Stuck at what is 'line number' in this context? I tried to force my way through it hoping context would fill it in but immediately got stuck at fractions like '1 / 3' followed by '1 / 4'.
If you scroll down just a bit, the article provides a live demo so you can play with the system and see what’s happening.
The “line numbers” (not a great name) are the column edges. So 1/3 goes from edge 1 (the left-most) to edge 3, spanning 2 full columns.
Line numbers are the dividing lines between columns. If you have 2 columns you’ll have 3 lines: |a||b| the two lines in the middle actually count as 1. Hence 3 lines. So 1/3 is not a fraction its column span. It means “start at line 1 and end at line 3”.
Might be the first time I've actually understood CSS grid. The numbering really helped!
Great article! Will be referencing it often.
You can make those numbers show up natively in Firefox too using the developer tools. (Not sure about chrome)
Solid article! Important point I didn't see covered / worth noting with grid & flex layouts is visual vs logical tab orders ... Looking forward to a solution in upcoming specs
https://developer.chrome.com/blog/reading-flow-display-conte...
Last year we published...
N.b there's been a weird trend for blogs to remove publish dates and it really compounds the issue when the contents then use relative dates. At least this one has a tiny "last updated" timestamp at the bottom...?
Does anyone know why the numbers are the gaps rather than the columns / rows? It's not exactly rocket science, but it took me a while to wrap my head around that, and it would have felt more intuitive for e.g. an item taking up the first two columns to be 1/2 rather than 1/3. I wonder if that's something to do with being used to arrays starting at 0, and if it has to be columns then using 0/2.
Should be 0-indexed or 1-indexed, but not mixed.
Probably thought 1-indexed is more understandable to regular people.
The interactive elements of the article made it click for me, the effort is much appreciated!
Highly recommended for CSS Grid is Jen Simmons Mondrian with auto flow. https://labs.jensimmons.com/2017/01-011.html. Try 'C' and 'D' then change the window size. Also the youtube video that goes along https://www.youtube.com/watch?v=qNtJ5p3h2A4.
Just very cool.
The one thing about auto flow I wish I understood was how to detect, and fill, gaps. If I have some random collection of differently sized objects, how do I ensure that auto flow leaves no gaps? Or even detect that so I can add something?
What a brilliant blog. Author puts a lot of love in it, that's clear! Thanks for sharing, read the whole thing. Made me feel kinda stupid for not using CSS Grid more... ;-)
Would like a tool like the one made for flexbox (to streamline
the process of creating responsive layouts): https://flexboxcss.com
Wow, I just love interactive blog posts like this. For grids I can really recommend just playing around with grid areas in a tool like https://grid.layoutit.com/
I've been using the site to plan my grid layouts for a couple of years now and it just makes spacing so much easier
Superb article. Things are so clear. MDN/W3C should hire him to do this for many web concepts.
Supplementary, by a CSS grid expert: https://www.youtube.com/watch?v=EashgVqboWo
The last layout strategy I was decent at was <table>, so you should be fine.
Grid is basically `<table>` with extra functionality (in fact in my project we are emulating table layout using CSS Grid with good results). If you can do <table> then you can do grid.
I'd say grid is table except not in the DOM itself.
Some consequences of that are that you can easily adjust the order and such. And just need to change one elements style to adjust the whole layout.
If you managed to understand floats (a rare feat) you'll have a blast with flex / grid :)
Floats are not weird. They were just utterly misused, using them for layout is an ugly hack.
They were conceived to float text (or other elements) around static elements. Think text floating around a picture, like this:
https://tco-forum-uploads.s3.amazonaws.com/original/3X/0/3/0...
If you were there with floats, Grid and Flex will be a walk in the park for you. Give it a day or two and try out a few layouts. And unlike the struggles with browsers, these two seems to just work. In-fact, they are kinda boring.
There are a lot of articles, some really good but I read through two of CSS-tricks articles and that is all there is.
- https://css-tricks.com/snippets/css/a-guide-to-flexbox/
- https://css-tricks.com/snippets/css/complete-guide-grid/
Those articles are my bible. I have them almost memorised but for the more esoteric things I still consult them. Invaluable resource!
Grid has a lot of features but flex is simple enough and still very powerful
I think you can get away without learning grids, but flexbox is a must - given its convenience over the old “float-hacks” and its omnipresence in modern CSS.
Besides the already mentioned css-tricks articles, I recommend checking out the guide to flexbox from mdn[1] (in the side menu there is also one for grids) as well as the reference to “CSS flexible box layout”[2]. These helped me get a deeper understanding about the concepts behind flexbox and how the properties and their shorthands actually work.
[1]: https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layou...
[2]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_flexibl...
I feel like flexbox is the float grid system done right, and you can lay out children either vertically or horizontally, whereas floats with the clearfix hack were only laid out as rows. But it's still mostly one-dimensional with possible wrapping, so the trick is to nest and stack. With grids it's different, a grid has a template and then the direct children occupy those predefined areas, which is more static than flexbox and the grid doesn't affect other nested elements, which is a limitation, but subgrid should change that.