How to build CSS grid layouts in 2021 — Web design tutorial

CSS grid is used by frontend developers anddesigners to build ALL kinds of modern web layouts and interfaces in fact, itsthe primary layout structure for apps like Slack and the Webflow Style panel itself. But it can be used to create anything frombasic structures to entire websites. Well cover grid-based layouts in 6 parts:well show how to create and configure grids, well talk about the magical div block,well use grid AUTO position to create an image grid layout, well use MANUAL positionand OVERLAPPING to create a four-quadrant hero section, well go into reusable layoutsusing grid template areas, and then well cover making grid layouts responsive to workon DIFFERENT devices. Now. Before we begin lets clear up something. Grids are GUIDES. Its no different than arranging apps andwidgets on iOS. (You can push things around, but the thingsINSIDE the grid will be GUIDED by columns…and rows.) And this is the DEFAULT behavior for CSS Grid(things are AUTOMATICALLY positioned…and they wrap to the next row when they run outof columns). But thats just the BEGINNING.Because you can do SO much more. So with that in mind, lets start with thebasics. ANYTHING can be a grid. Heres a section. Click grid? Now you have a grid. Heres a div block. Click grid? Now you have a grid. On the Add panel? Theres a grid you can just drag right in. Collection list filled with dynamic contentfrom the CMS? Set its display setting to Grid? Now you have a grid. Working on a late-night project and accidentallyspill coffee, causing your other hand to lean in just the perfect way on your macOS-compatiblekeyboard to press both the Command and E keys at the same time? Start typing Grid, press Enter. Now you have a grid. Now. Thats on Mac. Its different on Windows. Grimur? Grimur: Im working on a late-night projectand accidentally spilled coffee, causing my other hand to lean in just the perfect wayon my Windows-compatible keyboard to press both the CONTROL and E keys at the same time.McGuire: Start typing Grid, press Enter. Now he has a grid. And how do we use a grid? Well, we just put stuff inside. By default, things take up the available cells,and wrap to the next line automatically. In fact, new rows will be automatically created. And at any time, to edit a grid…press editgrid. Now youre editing the grid. When youre editing, you can add columnsor you can add rows to your grid. And notice how the contents automaticallywrap to fill up the space inside. Once were done editing the grid, letsclose out. And heres the first thing that might seemodd: if we want to drag an element to the bottom right cell? It just…doesnt work.But thats expected. Thats because elements added to a grid,by default, are AUTOMATICALLY positioned. If we want to manually position this? Just set it to manual. And we can now drag it wherever. Well cover this later on when we talk aboutManual position in more detail, but theres one, really important point to make here. This is a website we built in CSS grid. Except its not. Its Microsoft Excel. And in spreadsheets or tables, deleting arow or column usually DESTROYS the content inside. Grids on the web are different. BECAUSE theyre guides, deleting a columnor row might push things around, but its not deleting actual content. And thats the main idea: there is NO wrongmove you can make when creating a grid. Grids are non-destructive in that theyrejust GUIDES for the content well put inside. Lets edit our grid further. Lots of options here. And we can just click and drag so we can adjustthat space (you can adjust the GAPS between the rows and columns).But it gets better. Want to adjust the columns themselves? You can do this, too; you can adjust sizingon a column by clicking and dragging you can do this right on the canvas when youreediting a grid. By the way, FRs (the FR unit on these columns)? These are fractional units. Because before grid came out, wed manuallycalculate things like percentages, pixel values (and YOU can still use these)…but FRs replaceeveryone having to manage their own Cartesian coordinate systems in favor of something more straightforward.And it goes like this: Three columns? Each set to 1 FR? That means each will take up 1/3rd of thewidth. Four columns? 1 FR each? Now each takes up 1/4th. And the math is done FOR us, so if we wantthis column to be TWICE the width of the others, we just set it to 2 FR. Notice how everything else scales automatically.And one more thing to note here: we mentionedthe GAPS between each cell. You can change these gaps and FRs will STILLcompensate for that. Are FRs magic? No; theyre science. And also magic. When youre DONE editing a grid, rememberyou can ALWAYS come back and change things, but for now, we can just PRESS Escape, or,press the button that says done. So. Grids. We can make a grid, set some rows and columns,and start putting things inside. Theyre automatically going to positionthemselves, but we can deviate from that by setting one or more elements to MANUAL positioning. (We can then move it wherever we want insidea grid.) Lets move to the magical Div block.Because if you havent noticed yet, theressomething odd going on. There arent many practical layouts thatlook like THIS. And we get the question a lot, yeah, grid,but how do we USE it? Syntax aside, theres an important pointthere. Grid-based layouts often require NESTING things(headings, paragraphs, buttons, images whatever) grid layouts often require putting MULTIPLEthings inside single cells. So. Do we just set things to manual position anddrag them into the same cell? Well…no. Now theyre all stacked on top of one anotherin a mess. Enter: the magical div block. Its a div block. But were calling it magical. And the idea is this: we can just drag ina div block that TAKES UP a cell…we can place it wherever…and now we can put stuffINSIDE the div block. So if this is our grid, and we want thesethings inside, we put a DIV block in the cell. And we position the things we want…insidethe div block. The most PRECISE way to make sure wereplacing our elements is to use the Navigator (but well cover a shortcut for doing thison the canvas in just a bit).But thats the SECOND big idea (we coveredhow grids are guides for our content)…but the SECOND takeaway here is that grid CELLSarent actual containers (theyre NOT div blocks, and by default, they only holdone thing at a time). So div blocks give us the power to put MULTIPLEelements inside a grid cell. Those are our two takeaways: grids GUIDE ourcontent, and div blocks let us NEST multiple things inside any CELL in our grid. But lets make this REAL and put all ofit into REAL layouts. And to do that, lets do auto position FIRST…bybuilding this image grid. And this ones straightforward. For us, we have a blank section and a blankcontainer…and were going to use a Grid (just dragging in a GRID from the Add paneland were placing it in the Container this way we keep the grid and our images containedtowards the center of our design). But for now, lets add our images. As we know, to add stuff to our grid? We just click and drag it in.(WERE using images, but this could be headingsor links or div blocks or videos…). Lets edit our grid before we continue letsmake it a 4×4 (remember: we can ALWAYS change this). When were done? Lets stop editing. And lets CONTINUE dragging images inside. But notice how, like we covered earlier, nomatter WHERE we let go, content is automatically placed. The children of the grid (the IMAGES inside)are just wrapping around and filling up the available cells inside our GRID. (Its doing this automatically.) In fact, if we go in and edit again? We can CHANGE, for instance, the number ofcolumns. And again, in Excel or Numbers or Google Sheetsor with ice cube trays removing a column is HIGHLY destructive and destroys the stuffinside.But HERE…our images are fine. Theyre now just taking up fewer columns(they WRAP automatically). Once were done, lets head back out. And something to note here about SIZE… isthat these rows (the height of EACH row in our grid) this is automatically sized. And since the Grid (and the Container andthe Section) since none of these have a height set to them, ONE option is to justset a height on our Grid. Lets choose something like 800 pixels,but we can ALWAYS change this later.But right now its a LITTLE inconsistent these images have different aspect ratios; theyre all aligned to the top-left of eachcell… lets start to CONTROL that. With our GRID selected, lets look at ouroptions here. We can ALIGN… or justify any of the CHILDRENelements inside the Grid. Now. With IMAGES specifically, sometimes designerswant images like these to fit more consistently (to have the SAME row heights, and same aspectratios). And a great way to do that is fit (objectfit). Its 100% magic. And it WORKS (most of the time). Now. Before filming, we pre-applied the same classto each of these images. You can TELL… because it literally saysClass we pre-applied on each of the images. If we hadnt done that, we could alwaysadd a class later. But we DID. So. To fit the images EVENLY? We only have to do TWO things: (1) we setthe dimensions (we set 100% width…and 100% height). And (2) we USE object-fit. (Were doing all of this on the CLASS thatsbeen applied to the images). Well set our FIT… to Cover. And just like that, all the objects FIT insidetheir cells.And notice how the row heights are perfectlyeven. Now. HOW is this grid NOW being sized? Well lets go back a moment, because weset the height to 800 pixels a minute ago. What happens if we REMOVE that height on theGRID? Does it go to zero? Almost. In fact, if you look closely, it still hasthe GAP (the space between the rows). But because we DEFINED the height of EACHimage as 100%, theyre only going to be as tall as the ROWS themselves. Which dont have a height. Which is why this whole thing has collapsed.So. If we put back a number? (If we give the grid a height?) It sizes accordingly. Of course, the blue property labels TURNEDblue because weve changed something on this class. And, as we know, the AMBER property labelsshow that a value on this class is coming from somewhere ELSE. But what about PINK labels? Lets just pick ONE of these images andSPAN it (were grabbing the corner…clicking and dragging…to span). So instead of ONE cell in our grid, it spansMULTIPLE cells. And we can see it in the Style panel: we seeHOW many columns and how many rows it spans. And THAT information is stored in the ELEMENT. Thats what pink labels mean this doesNOT apply to the whole class we pre-applied earlier called class we pre-applied it JUST affects the SELECTED element. Thats automatic positioning using an imagegrid.What about manual positioning and OVERLAP? To go over THAT, lets build this hero section. But to GET there, lets first make our herosection a side-by-side (well talk about WHY in a moment). For this, were just going to drag in aSection element (dragging it right into the page body). And well set a height (lets set theminimum height to 70vh this way its 70% the height of the viewport). And all we have to do to make it side-by-side? Just set the Section…to GRID. (Two columns…now we can build our side-by-side.) So lets start by putting an image on theleft. Lets go to the Assets panel and drag inthe image we want on the left side (dropping it right into our Grid section).And by default (as we know), it goes in theFIRST available cell (top-left). And we want our image to take up the fullspace available. Well, fortunately, we just brushed up on objectFIT. And like we did before, we do TWO things tomake this work perfectly. We can (1) add our dimensions (set both widthand height of our image to 100%)…and (2) we can set our FIT to Cover. (And now our IMAGE…is COVERING the firstcell.) But thats not what we said wed build.With our image selected, lets span it. (We want to click and drag to SPAN this elementacross both cells in our left column.) And. Thats it. Again, spanning is THAT simple. Want to span the TOP two cells? Click and drag…and its spanned. Want to put it back? Span it back. Span. The word sounds weirder the more you say it. Thats our left side of the side-by-side. What about the right one? Well heres where we go back to our magicalDiv block. Well drag a div block right into the grid,and it can be placed in the next available cell. To span it? Well just span it.And thats the side-by-side. If we want to put a heading inside? Lets demonstrate the WRONG way to do this first. Drag the heading…over to the right here? Let go? This…is NOT what we wanted. Remember: dragging something into a Grid isDIFFERENT than dragging something into a Div block INSIDE a grid. So to make sure we get it right, lets undo…andtry that again, but this time lets hold down Command on macOS or Control on Windows…andjust drag the heading into the Div block.We can verify this in the Navigator. (The heading is in the div block…which isin the grid.) Lets do the same with a paragraph thistime we can drag the paragraph RIGHT into the Navigator ITSELF (right under the heading). And finally, lets add some buttons. This time (and because weve developed ahabit of showing DIFFERENT ways to add things)…with our Paragraph still selected, we can add somethingRIGHT after it. Well use Quick Find. Which we can add by pressing Command + E (orControl + E on Windows) and starting to type “button”. And it’s not just elements (it’s even otherlayouts we’ve designed and saved). Once we select it? It’s placed right after the paragraph. NOW. How do we vertically center this stuff? A couple ways. We can select the grid ITSELF. And if we want the children to align to theCENTER…we just…align to the center. Or, if we want to undo that, we could useflexbox (we could apply flexbox to the Div block itself, and just make sure its setto Vertical, and we can mess with our alignment or justification controls to make it workhow we want it to work).And if we select our Grid again, and we goto EDIT? We can adjust or even REMOVE the gap (justset the gap there to ZERO) so now its truly a 50/50 split with the image. And for our content on the right? We can USE our Div block (by the way, letsname this something like Hero content to keep things organized). But wait a moment. This section is called MANUAL position. And so far…everything uses AUTO positioning. (Weve COVERED spans, but we havent usedMANUAL position on this layout). So. What is our GOAL? Our goal… is to have our hero content onthe bottom-right cell. How do we do that? Well…we just set our image on the left tomanual position…and we set our div block on the RIGHT to manual position as well. And now? We can select and SPAN our image to take upall FOUR cells.And if we want our magical flexbox Div blockto position on the bottom right? We span it DOWN so it takes up the bottomright cell. So now we have a BASIC overlap. Is it stunning? Not yet. A couple things here: (1) we need to makethe background more not terrible. So in our Div block (the Hero content block),we can add a background color. But (2), we should go in and figure out whatsgoing on with the row height. Because you might notice that the HEIGHT ofthe second row is no longer HALF because we have the height of the CONTENT added tothe bottom row, too.Could we set each of the rows to 1 FR? Can we use fraction units on both? Well, yes. In fact, thats going to still respect thecontent inside, but give us more even rows. But we could also make the BOTTOM row Auto. Thatll mean the SIZE of the bottom rowis determined ONLY by the content inside. And when we do that, we can now add breathingroom by adding PADDING (just add some padding to the Hero content block). But thats MANUAL positioning and overlapping. What about reusable layouts? This part goes pretty quickly. Because, heres a section. Lets give it a height (lets say 750pixels). And lets turn it into a grid. But THIS time, lets set up our layout INSIDE of Grid. And no matter how we CONFIGURE our grid…we can define Grid areas (we just click the little plus to start defining a grid area). And this lets us define REGIONS of our gridthat can hold content (in other words, were defining the individual PARTS of a layout).But the REASON this is important is becausewe can REUSE these entire layouts in other parts of our project. But heres the big thing. This layout? Its part of the CLASS. In fact, we can rename this class Examplelayout (there are more clever options)…and we can apply it we can apply that class to another section. So lets add ANOTHER section underneaththis one (of course, you could add this to ANY page in the project). And what do we notice? Well, nothing yet. We have to apply the Example layout class. But NOW what do we notice? Its layout isnt just following the sameRULES, but also…its blank. So what if we add OTHER stuff to this layout? (These are ALL just div blocks with some stuffinside again, were using plain old div blocks we sometimes call magicalto serve as little CONTAINERS containers that we put inside grid cells and grid areas.) And what happens if we edit our grid? Is it unique? No.BECAUSE this is a reusable layout, we candefine our areas and even REDEFINE our areas after the fact. And the layout throughout the project changes. Put more practically? We can use AREAS to define entire layouts. That means a change on ANY ONE AREA will affectALL Grids that are using that class. But THATS grid template areas. Lets finish up by talking about responsivedesign. Grids are responsive by DEFAULT. BECAUSE the width of each column is usuallysized with FRs, itll generally respect those proportions and the content inside. And as the browser gets narrower, everythingwill scale accordingly. But if you want to change something in anotherview? Want to design for different devices? We can make that change. Even if we change the number of columns, andgrid children set to auto? (If the children of a grid are automaticallypositioned?) Theyll wrap responsively just like youdexpect.Come back to desktop? Everythings as it was. Thats because changes cascade down FROMthe base breakpoint, meaning when you change stuff on desktop, that affects tablet andmobile views. And things you add or change on tablet affectmobile. (Theres a pattern here.) Mobile landscape changes affect mobile portrait. And as we go down the different views, changesonly affect smaller devices. You will notice, though, that if you havesomething MANUAL? (If somethings set to manual position?) It can get stuck that way if you dont TELLit what you want it to do on, for example, a smaller breakpoint. Even if you remove a column, if somethingwas placed there manually, you have to either MANUALLY place it in a new column, or setits position to auto. Now. One thing to note about manual position: ifyoure repositioning an element VISUALLY on the canvas (if youre moving it aroundin the Grid)? It has NO effect on the actual document order.Why is that important? Well, if youre tabbing through or usinga screen reader like VoiceOver, by default, its going to follow the order you see inthe NAVIGATOR (the document order). With THIS element selected, notice how itsposition in the Navigator DOESNT change, even though were moving it around usingManual position (by the way, this can apply to Grid Areas, too). And this is CRITICAL to keep in mind as youreORGANIZING content in a grid: make sure the ORDER (the way you want someone to INTERPRETyour content) make sure thats set in the Navigator, THEN make visual adjustmentsas needed. Not only is this LOGICAL, and correct, andefficient, but its a step in the right direction for developing more accessible websites. But thats an overview of responsively designingwith CSS grid. So. Our two big takeaways: (1) grids serve asGUIDES (deleting a row or column doesnt delete the stuff inside. And (2) grid cells usually only hold ONE thingat a time. So putting a DIV BLOCK inside a cell unlocksSUPERPOWERS…and lets us put other stuff inside that Div block.So. Lets do a quick recap of Grid. We can add a grid just like any other element. We can drop things in a grid and theyreautomatically placed. Theyll fill up empty space… unless, ofcourse, you set something to manual, in which case you can get that child to do anythingyou want. Like parenting. Except not at all. We can span things and overlap things…wecan create reusable layouts which, when we APPLY that class to other stuff, that layoutcarries OVER. And we can design responsively (taking a gridlayout that might work GREAT on desktop, but maybe removing some columns on smaller views). Now. We cover a lot more of this…like auto-fit,the dense setting in grids, designing for LARGER breakpoints, when to use flexbox versuswhen to use GRID all of this is on Webflow University. So check that out if you havent already. But thats an overview of grid…in Webflow..

Command on macOS

As found on YouTube

Share this article

Leave a comment