24 ms·
CSS Grid for UI Layouts
- exogen 9y agoThe 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 9y agoUsing 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 9y agoI'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.
- jsgo 9y agoSo I found MDN's documentation on it (https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-areas 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.
- benjaminjackman 9y agoI 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 9y agoThanks 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.
- dmix 9y agoWoah, I didn't fully understand how that works given the OPs description, but after seeing it in action... that's amazing!
- rhizome 9y agoI'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.
- antibland 9y agoThe class names don't matter. Each grid-template-areas value has to match the grid-area value (the actual grid item being placed).
- rhizome 9y agoRight, but do you see how you've used the same terms for both?
- antibland 9y agoI 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.
- metafunctor 9y agoThe 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.
- Majora320 9y agoautoplay can be disabled in Firefox with a simple configuration tweak, and I'm sure it can be in Chrome as well.
- johnhenry 9y agoThinking about how difficult this must have been to do with 1960s analog video technology makes this feature more impressive.
- darepublic 9y agocombine this with rem sizing units for font and padding -- now you're playing with power
- pasta 9y agoNot 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.
- osrec 9y agoAlso, size your root element font using vw or vh. Then things become really responsive when done right.
- JimDabell 9y agoPlease 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.
- osrec 9y agoWith 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.
- themarkn 9y agoIt'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.
- 9y ago
- chrisweekly 9y agoFantastic 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.
- interfixus 9y agoI 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.
- JimDabell 9y agoBecause 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.
- interfixus 9y agoYes, 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.
- JimDabell 9y ago> 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.
- interfixus 9y agoNot 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.
- mikevm 9y agoGiven CSS Grid, what role do frameworks such as Bootstrap play?
- Flavius 9y agoMaybe some cool defaults? Colors, buttons, typography etc.
- bergie 9y agoI 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.
- monkeynotes 9y agoUI 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.
- Hedja 9y agoUnderstanding 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.
- Raphmedia 9y agoSuch 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.
- sumoboy 9y ago
- stupidcar 9y agoThe 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.
- methyl 9y agoHow CSS Grid is non standard? It's defined by W3C: https://www.w3.org/TR/css-grid-1/ https://www.w3.org/TR/css-grid-1/
- yosamino 9y agoYou 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.
- sizzle 9y agoI have this recurring dream that I'm late for a final exam. Long term memory can be evil sometimes.
- superkuh 9y agoI 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_ 9y ago87% globally seems pretty good. Those without it now probably won't ever get it.
- Teichopsia 9y agoHere'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
- drcode 9y agoGoddamit, this actually makes sense. Guess I need to learn CSS grids now- Yet another task to fill up my already overflowing todos.
- stctgion 9y agohttp://cssgridgarden.com/ http://cssgridgarden.com/
- knowuh 9y agoCutest thing ever.
- jsgo 9y agothat'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 9y agoWhen 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.
- jsgo 9y agoBut 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.
- darepublic 9y agocan 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?
- pavlov 9y agoFloat 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).
- ino 9y agoFlexbox: 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 9y agoI'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-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.
- mephitix 9y ago>> 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 9y agoCSS 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 9y agoI 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 9y agojQuery in three lines. Awesome. const $ = (selector) => document.querySelector(selector) const $$ = (selector) => document.querySelectorAll(selector) const on = (elem, type, listener) => elem.addEventListener(type,listener)
- Felk 9y agoconst $ = document.querySelector const $$ = document.querySelectorAll :)
- Etheryte 9y agoWhile 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.
- RussianCow 9y agoDoes 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 9y agoAutoprefixer should take care of this for you. You write standard grid layout and it works on IE11.
- RussianCow 9y agoMy 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 9y agoAutoprefixer 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.
- ksenzee 9y agoAutoprefixer 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 https://codepen.io/ksenzee/pen/OzRejj
- JimDabell 9y agoThis 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.
- deckar01 9y ago10 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.
- hexane360 9y agoMathematicians will have generalized CSS into arbitrary dimensions long before CSS grid is widely adopted.
- adregan 9y agoI 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.
- dredmorbius 9y agoCSS Tensors. You heard it here first.
- andybak 9y agoDo CSS properties accept quaternions?
- SiVal 9y agoCSS 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 9y agoCSS Lambda Calculus
- 9y ago
- nukeop 9y agoI 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 9y agoDid you read the article? It's kind of about exactly why that's not the case.
- nukeop 9y agoThe 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 9y agoYeah, 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 9y agoThat'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.
- rimliu 9y agoTemplate 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.
- digi_owl 9y agoI find it hilarious that after all these years we are back at working with grids.
- knowingathing 9y agoGrids 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...
- megaman22 9y agoCool, so I can do what I've been doing with WinForms TableLayouts since forever /s
- rimliu 9y agoYou 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.
- keithnz 9y agoI look at the usage data of our website and see so many IE 11 connections and I sigh.
- ygra 9y agoHow different is the older specification it supports? Also it's prefixed, so it could in theory be specified without disturbing newer browsers.
- icemelt8 9y agoWhat was the point of this article? other than having SEO internal linking?
- pjmlp 9y agoI love CSS Grids, finally a bit of native layouts sanity on web development (flexbox still wasn't quite it).