Hacker News new | past | comments | ask | show | jobs | submit login
Faster Layouts with CSS Grid and Subgrid (hacks.mozilla.org)
244 points by feross on Oct 18, 2019 | hide | past | favorite | 84 comments



Good stuff. Keyboard clacking during screencasts is a non-starter for me tho.

I really like Jen Simmons's videos on CSS layouts. (https://www.youtube.com/channel/UC7TizprGknbDalbHplROtag/vid...)

Before this month, the last time that I made a layout with CSS floats were still in style. When I decided to really learn modern CSS this month even starter videos like "Basics of CSS Grid: The Big Picture (https://www.youtube.com/watch?v=FEnRpy9Xfes)" were over my head.. I'm a back-end developer, I'd never used Flexbox let alone Grid. As I watched Jen's videos I scribbled down what she was excited about and then started reading "CSS: The Definitive Guide (https://www.amazon.com/CSS-Definitive-Guide-Visual-Presentat... cover to cover.

I'm really glad that I watched Jen's videos first. Having some best practices in my head before I learned the mechanics of Flexbox and Grid helped crystallize everything. Now that I'm basically through CSS: TDG I'm re-watching her videos and getting even more out of them.


> Good stuff. Keyboard clacking during screencasts is a non-starter for me tho.

Funny, I often get compliments on the clacking of my mechanical keyboard in screencasts and livecodings. Creates a soothing background noise.


Clacks drive me up the wall. Having a table mounted mic in a podcast gets to me too. I can't concentrate if I keep hearing elbows hitting a table through a mic stand.

It's more editing work but I like to split out the screen recording, VO, and PTC. Bonus, you can get rid of jump cuts and other weird edits by cutting to the screen recording just before you messed up your line.


What’s VO and PTC?

My mic is on a boom with a shock mount so the clacks really are just mellow background noise. I hate the loud bangs too.


VO -> Voice Over I assume. No idea what PTC is.


I think it's "Piece to Camera", which took quite some digging to find!


Yep. PTC is Piece to Camera and VO is Voice Over.


Push to chat, no?


The context is video creation: "It's more editing work but I like to split out the screen recording, VO, and PTC."

Piece to camera is talking directly to the camera, unlike a voice over while showing something else. Makes sense to me, but I'm guessing a bit.

How would "push to chat" fit in? I don't recognise it.


Was thinking in context of gated voices, background noise etc. Think it’s actually push to talk, so I’m not right on reflection.


I was thinking it's odd because, in the one video from this article I watched, the keyboard sounds were among the quietest and least noticeable I've ever encountered.


I’ve had great feedback on my css grid crash course video: https://m.youtube.com/watch?v=SPFDLHNm5KQ


I've come to prefer flexbox over grid, the main reason being that it gives much more sensible behavior on different screensizes. When you want to lay out for different sizes of screens, grid usually means a completely separate layout inside a media section, while flexbox's wrapping behavior seems to smoothly transition between wide and narrow screens with only a few margin/width adjustments. There may be a sane way to get the same behavior with grid auto-flow, but if there is, I haven't figured it out.

One thing I'd like to try, but have never had the budget for, is completely isolated grid layouts for different sizes. That is, all the layout is in mutually-exclusive media sections. This has a higher up-front cost, but I suspect in the long run, the higher up-front cost would be outweighed by having layouts more fine-tuned for the screen sizes, and more decoupled so you don't have to worry about changes in desktop-size layouts affecting mobile-size layouts.

Flexbox also has a significantly larger browser share than Grid on CanIUse.

Really though, I'm greatly relieved to see browsers start implementing some layout tools that corresponds to how people actually think about layouts. The float years were dark times.


Oof. You are definitely missing the entire point of CSS Grid.

CSS Grid is a two dimensional layout tool. Flexbox is one.

CSS Grid is for architectural layout. Flexbox is for alignment and flow layout.

CSS Grid was enabled across all major platforms by October 2017. You've had two years to figure that out. You want it on IE? Then use CSS Grid's original syntax because Microsoft supported Grid first.

The browsers haven't "started implementing some layout tools" --- they literally did it, en masse, in 2017. Grid was available for everyone's use by October.

Do yourself a favor and work through the examples here: https://gridbyexample.com/

Do yourself another favor, and stop trying to make different layouts for all the different sizes. Or, go with insanity - your call. Grid is for responsive layout, out of the box; no negative margins, no weird padding, no inane extra workarounds just to get something to line up.

Once you understand that CSS Grid is the tool we have been waiting for since the late 90s, and that it, NOT Flexbox, is the sane, maintainable, future-proof layout tool for pages, and then using Flexbox within it to adjust flow and tempo -- you will/can spend a lot more time playing with things for the sake of play, and not for the sake of debugging.

Good luck.


While I agree with almost everything you said, did you need to be condescending while doing it?


My thoughts exactly. Let’s all be adults here.


These is value to vehemence in arguments.


`s/vehemence/passion/` and I might have agreed. The words may be similar, but there is a distinct difference between them. Had OP just showed passion for the topic without being vehement, I think it might have landed a lot better.


> CSS Grid is a two dimensional layout tool. Flexbox is one. >CSS Grid is for architectural layout. Flexbox is for alignment and flow layout.

I agree with the first (it seems impossible not to) but I think the 2nd is kind of a misconception. That grid is for “architectural layout” ... it’s for any two-dimensional layout, any time, any place. And flexbox is often totally appropriate for laying out entire pages or large sections of pages, if 2 dimensions of flexibility are not needing to be controlled. You can have grids inside your flex items inside your grids inside your flex items as needed.

The decision of layouts having to look a certain way at different sizes unfortunately is often made long before any code is written to implement a design in my experience. Not much the implementation person can do except maybe push back, but it can be a tough sell to ask for an approved design to change so that the underlying code can be less hacky.


> The browsers haven't "started implementing some layout tools" --- they literally did it, en masse, in 2017.

Fun fact: Grid support in Blink and WebKit were added by the same people. https://blogs.igalia.com/mrego/2017/03/16/css-grid-layout-is...


Grid and flexbox have different uses and values. I wouldn't give up on grid. There are things it does that Flexbox fails spectacularly at. (absolute layout control for one...) But also flexbox does a few things grid simply cannot. So it's good to know both.


Sadly, I haven't been able to find any benchmarck comparing grid vs flexbox, despite layout being a common bottleneck.


They have different use cases. The rule of thumb is to use Flexbox if you're laying out content along the X or Y axis and Grid if you need to lay it out over both the X and Y axes.


That's an okay rule of thumb, but I find myself using grid more and more for traditional flexbox applications like a horizontal list of cards that wraps. Little things like grid-gap (flex child margins are a constant source of pain) and auto-fill with minmax [0] make a big difference to me in rapid prototyping.

[0] eg: grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));


Firefox supports grid-gap for flex, but I no other browsers do yet.

https://caniuse.com/#search=gap


This is a very good rule of thumb.

Grid is great for the layout of the whole page (header/content/sidebar/footer) or specific gridded containers.

Flexbox is great for everything else, and specifically what you said about in one dimension, like form label/input or a repeating set of thumbnails, or justified buttons.


I agree for the common case, but CSS grid even for one axis can be better, especially for gutter/gap.


It's nice to be in a place with CSS where we're talking about all of the good ways to do things rather than telling each other "if you abuse this feature you can accomplish the task in 2 of the major browsers. YMMV."


It would be nice to find a document showing how to do some examples in both Grid and Flex and compare the amount of markup needed, also pros and cons of each for each example


I have been in desktop and mobile dev my entire career. Starting doing web dev 12 months ago for a new job. Never once have I thought to myself "I should figure out what float does".

Grid + Flex + Block + Absolute covers all layout needs. It's funny to me because conceptually these ideas have been around on desktop/mobile layout systems forever. That they are only now making it to the web is insane.


To be fair, we didnt get Grid till 2017. So.. we finally have (nearly) all the tools we need. Maybe. lol

Float is still very useful for paragraph wrapping around media, for basic alignment etc, when you do not need an entire flow of content to be under the management of flexbox. Less is more.


Floats are still useful, not for the same things you would use grid/flex but still has utility, so its good to know about them.


For what?

I literally haven't used float since grid/flexbox hit adequate market share on CanIUse, and I've been doing web development full time this whole time.


Floats are still useful when you want to express structured document flow layouts with illustrations for nearby body text, side-nav link boxes, aligned or otherwise flow-parametered effects such as initials, syndicated/contributed content, or when you just want to float text around images.


Every time I thought I have needed float, I have always later found a cleaner way to do it without float.


That's probably because float is almost always used for things which it's not designed for. For cases like what the parent described, which float is actually meant for, there is no alternative.

A good example is the floating picture boxes next to paragraphs on Wikipedia. How would you implement such a feature without floats?


Floats should now only be used for what it's named for, to float around other elements:

https://developer.mozilla.org/en-US/docs/Web/CSS/shape-outsi...

(shape-outside is super buggy though)


For having an image where text flows around it once it finishes. It’s basically good for some text flowing stuff. Which makes sense, that’s what it was designed for originally.


On my website I have a sidebar (on large enough displays) where I put sidenotes (which I typically prefer to footnotes). https://chrismorgan.info/blog/dark-theme-implementation/ is an example of an article with both float-based sidenotes and grid-based figure captions in that sidebar. Look at what happens on mobile-sized displays, too. https://chrismorgan.info/blog/2019-website/ is an example of where float really shines on this, with the second sidenote automatically moving down the page due to the length of the first sidenote.


For when you move to a company where the current canIUse marketshare for grid/flexbox is no longer "adequate."


Flexbox is great if you don’t have wildly different layouts across different screen sizes.

If your layout is different enough that you’ll need media queries then you’ll want to use grid anyways.


> If your layout is different enough that you’ll need media queries then you’ll want to use grid anyways.

Ehhh, not really.

A common case is items laid out as boxes. On desktop I want them in rows of 3 to 5 (perhaps more on wider screens, but often this starts to look stupid beyond 4 or 5 so you set a max width for the container). And in mobile we want 1 item per row. With flexbox, you just change the width of the items from 33.33% to 100% in the media query, maybe with some adjustments to margins, and you're golden.


Now consider the same setup, but let's say you wanted all the boxes to be the same height: that would only be possible with grid, or by setting the heights manually


Flexbox is a pain to do gutters


Please take into account current support for subgrid [1].

My first time redoing quite complex checkout table with mobile support was a nightmare. I only realised I needed something more halfway along the process. Found out it was subgrid I was looking for and they figuring out there was no current browser support.

But using a oneliner like `grid-template-columns: repeat(auto-fill, minmax(30rem, 1fr));` too almost fully create a grid system is pretty amazing and something you can use right now.

1. https://caniuse.com/#feat=css-subgrid


wow, you're not kidding. only latest FF supports subgrid ?!


Yes - it came out earlier this week or end of last week. But CSS Grid has been available since 2017. So, we are able to still solve a lot of layout issues with grid, than leaning 100% on flexbox.

Every tool for its purpose! We have nearly a full toolbox on the CSS side of things. Happiness.


not latest, but nightly FF. That's a pretty big non-starter.


Support is coming tho. Always good to hear about what's next.


I've gotten a lot of the benefit of subgrid by using display:contents


Faster as in less time to author or as in better performance?


Based purely on the article content, it appears to be "less time to author":

"CSS Grid has made my layout process faster and simpler, with more flexibility. We can get started with a few basics, and the fallbacks don’t have to be overwhelming"


I assume the former. From the article:

"Don’t let that stop you: CSS Grid has made my layout process faster and simpler, with more flexibility. "


Grids and flexbox are on par with CSS tables for layout performance. Slow as hell to reflow.


All I want is a sticky, permanent header and footer and the rest of the page for text. (without the text going behind the footer/header) Can grid do this? I really don't like using javascript frameworks, I'm trying hard to keep my stuff pure html5/css3.


  .foo {
    display: grid;
    grid-template-rows: 10% 80% 10%;
    height: 100vh;
  }

  <div class="foo">
    <div>header</div>
    <div>text</div>
    <div>footer</div>
  </div>


That'll still shrink/stretch the header/footer based on window size, which usually isn't what you want (headers and footers usually being a static height). Really, this layout flows from top to bottom, so my instinct wouldn't even be to use grid - just leave the divs as blocks and give them the appropriate height:

  <div>
    <div class='header'></div>
    <div class='content'></div>
    <div class='footer'></div>
  </div>

  .header { height: 30px; }
  .footer { height: 20px; }
  .content {
    height: calc(100vh - 50px);
    overflow: auto;
  }
Bonus: If you have to support it still, this version works all the way down to IE9.


Don't think that has the desired effect; at least if I understood the request properly.

The text area won't get a scrollbar when more text is added to fill the view area. It seems in this case you would have to manually ensure that the text you gave could fit in 80% of the screen, or bad things happen visually. Also, the header and footer aren't permanent, they are affected by the entire-page scrollbar.


All you need is an `overflow-y: scroll` on the text element, and it will work as desired. The whole page won't have a scrollbar, because no content will be overflowing past it's boundaries.

Grid is ideal for these kind of layouts.


Thanks, that worked. Although I did still have to suppress the page scrollbar with "body { overflow-y: hidden; }" Not sure why.


Might need to use normalize or reset to deal with margin collapse, even then I’ve noticed the behavior at random times. The CSS box model is simple yet obtuse all at once.


HTML Frameset/Frames used to do that quite nicely. I'm not sure why they were removed in newer HTML standards, with no good replacement.


If the header and footer are permanent, what does the text do as you scroll the page if not going behind those elements?


Maybe they want to avoid breaking scrolling with space and page down, which so many sites with headers and footers do by having the covered up text still count for positioning.


use the following attr on the element and put it on top for the header and bottom for the footer.

position: fixed;


To prevent header and footer eating text and nav? Also doesnt using fixed take it out of the grid?


You don't want those elements part of your grid.


Really interesting. Didn't even know that this existed! Will definitely be checking it out and using it in future projects!


(video)


So I'm working on a replacement for HTML and CSS. Right now it's written in JavaScript and it renders to canvas.

The reason I'm posting here is because you can write your own layout components in my system. So if you have a new idea, instead of waiting years for it to get standardized and supported by the browsers, you can just roll your own idea and run it in anywhere without any fuss. (Flexbox took years to do something that should have only taken days.)

Live demo: http://doc-test.maxharris.org/ (NB: it doesn't support mobile touch events yet, so try that out on a desktop browser.)

The framework used by the demo: https://github.com/maxharris9/layout

If you want to get in touch with me about this thing, I'm maxharris9 on twitter.


It looks like you're reinventing Adobe Flash, but this time without a browser plugin and with even less accessibility.


Unlike Flash, my project is completely open. The README clearly states my plan for accessibility. Want to help me make it accessible?


JavaScript is like the worst alternative to HTML and CSS when it comes to performance, dependencies and accessibility.


Why do you believe that is the case? And what can be done to change that situation for the better?

Finally, why is JavaScript so popular? Why is driving the fact that more and more of the web getting rebuilt in JavaScript?


> Why do you believe that is the case? And what can be done to change that situation for the better?

The current HTML/CSS rendering is currently done by the browser. That part is native which means it can benefit heavily by the resources available that way (usage of the CPU/GPU, direct access to memory, etc...). It's also made by a bunch of people, with years of experience in the domain, they can make all this

Your solution would put this all on the Javascript side, which is already often put to its limits with our current usage.

React seems like a better solution. It render directly to HTML/CSS, so it profit from the browser performance to render it, but you can replace the rendering with something else (like React Native).


Primarily because JavaScript was the only language provided via browsers for dynamic scripting, so they didn't have to compete or care that much about performance optimizations. Also, browsers have become bloated virtual machines that try to cater to companies that want to track things like mouse and keyboard activity, rather than user privacy and consistency for uniform experiences.

JavaScript is so popular because a majority of developers started with with web development, and a majority of the money flowing into development was/has been focused on gathering user information and pushing ads for additional revenue, not delivering quality content using a consistent interface.


People were doing this with Java applets 20+ years ago. The first thing I noticed is I can't copy-and-paste.


I'll try doing something about that, but browsers control the clipboard in a pretty manipulative way. My current opinion is that they should allow apps to request clipboard access, rather than trying to restrict them completely as they do today.


Cool project. One thing I noticed is that when I zoom in, the font becomes pixelated. For people with poorer vision, HTML and CSS has a great advantage in that you can zoom in with most browsers and your fonts always look super sharp.


Thanks! I'll do my best to fix that zoom issue!


This sounds kinda like what the Layout API in CSS Houdini aims to do (though I don't know much about the current status of it).


If you're the ones that downvoted me, can you please explain why? I'm dedicating my life full-time to working on this, and I don't understand why this would offend you.

If the trouble is about accessibility, please read my README! I care about that, too, and I would love help!


Not the downvoter, but...

I dont think this comment should be here on this post. The only tie-in is layout.

It should be a show in instead.


D'oh! I forgot all about that! I'm not trying to be spammy. I'm just trying to show that there is a completely different way of doing layout.




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

Search: