CSS Grid Layout Module Level 2

The second iteration of CSS Grid is already in the works and the public editor’s draft was released last week! While it is by no means the final W3C recommendation, this draft is the start of discussions around big concepts many of us have been wanting to see since the first level was released, including subgrids:

In some cases it might be necessary for the contents of multiple grid items to align to each other. A grid container that is itself a grid item can defer the definition of its rows and columns to its parent grid container, making it a subgrid. In this case, the grid items of the subgrid participate in sizing the grid of the parent grid container, allowing the contents of both grids to align.

The currently defined characters of subgrid items are particularly interesting because they illustrate the differences between a subgrid and its parent grid. For example:

The subgrid is always stretched in both dimensions in its subgridded dimension(s): the align-self/justify-self properties on it are ignored, as are any specified width/height constraints.

In addition to subgrids, aspect-ratio-controlled gutters and conformance are also defined in the draft and worth a read. It’s great to see so much momentum around grids!

Direct Link to Article — Permalink


CSS Grid Layout Module Level 2 is a post from CSS-Tricks

Counting With CSS Counters and CSS Grid

You’ve heard of CSS Grid, I’m sure of that. It would be hard to miss it considering that the whole front-end developer universe has been raving about it for the past year.

Whether you’re new to Grid or have already spent some time with it, we should start this post with a short definition directly from the words of W3C:

Grid Layout is a new layout model for CSS that has powerful abilities to control the sizing and positioning of boxes and their contents. Unlike Flexible Box Layout, which is single-axis–oriented, Grid Layout is optimized for 2-dimensional layouts: those in which alignment of content is desired in both dimensions.

In my own words, CSS Grid is a mesh of invisible horizontal and vertical lines. We arrange elements in the spaces between those lines to create a desired layout. An easier, stable, and standardized way to structure contents in a web page.

Besides the graph paper foundation, CSS Grid also provides the advantage of a layout model that’s source order independent: irrespective of where a grid item is placed in the source code, it can be positioned anywhere in the grid across both the axes on screen. This is very important, not only for when you’d find it troublesome to update HTML while rearranging elements on page but also at times when you’d find certain source placements being restrictive to layouts.

Although we can always move an element to the desired coordinate on screen using other techniques like translate, position, or margin, they’re both harder to code and to update for situations like building a responsive design, compared to true layout mechanisms like CSS Grid.

In this post, we’re going to demonstrate how we can use the source order independence of CSS Grid to solve a layout issue that’s the result of a source order constraint. Specifically, we’re going to look at checkboxes and CSS Counters.

Counting With Checkboxes

If you’ve never used CSS Counters, don’t worry, the concept is pretty simple! We set a counter to count a set of elements at the same DOM level. That counter is incremented in the CSS rules of those individual elements, essentially counting them.

Here’s the code to count checked and unchecked checkboxes:

<input type="checkbox">Checkbox #1<br>
<input type="checkbox">Checkbox #2
<!-- more checkboxes, if we want them --> <div class="total"> <span class="totalChecked"> Total Checked: </span><br> <span class="totalUnChecked"> Total Unchecked: </span>
</div>
::root { counter-reset: checked-sum, unchecked-sum;
} input[type="checkbox"] { counter-increment: unchecked-sum;
} input[type="checkbox"]:checked { counter-increment: checked-sum;
} .totalUnChecked::after { content: counter(unchecked-sum);
} .totalChecked::after { content: counter(checked-sum);
}

In the above code, two counters are set at the root element using the counter-reset property and are incremented at their respective rules, one for checked and the other for unchecked checkboxes, using counter-increment. The values of the counters are then shown as contents of two empty <span>s’ pseudo elements using counter().

Here’s a stripped-down version of what we get with this code:

See the Pen CSS Counter Grid by CSS-Tricks (@css-tricks) on CodePen.

This is pretty cool. We can use it in to-do lists, email inbox interfaces, survey forms, or anywhere where users toggle boxes and will appreciate being shown how many items are checked and how many are unselected. All this with just CSS! Useful, isn’t it?

But the effectiveness of counter() wanes when we realize that an element displaying the total count can only appear after all the elements to be counted in the source code. This is because the browser first needs the chance to count all the elements, before showing the total. Hence, we can’t simply change the markup to place the counters above the checkboxes like this:

<!-- This will not work! -->
<div class="total"> <span class="totalChecked"> Total Checked: </span><br> <span class="totalUnChecked"> Total Unchecked: </span>
</div>
<input type="checkbox">Checkbox #1<br>
<input type="checkbox">Checkbox #2

Then, how else can we get the counters above the checkboxes in our layout? This is where CSS Grid and its layout-rendering powers come into play.

Adding Grid

We’re basically wrapping the previous HTML in a new <div> element that’ll serve as the grid container:

<div class="grid"> <input type=checkbox id="c-1"> <label for="c-1">checkbox #1</label> <input type=checkbox id="c-2"> <label for="c-2">checkbox #2</label> <input type=checkbox id="c-3"> <label for="c-3">checkbox #3</label> <input type=checkbox id="c-4"> <label for="c-4">checkbox #4</label> <input type=checkbox id="c-5"> <label for="c-5">checkbox #5</label> <input type=checkbox id="c-6"> <label for="c-6">checkbox #6</label> <div class=total> <span class="totalChecked"> Total Checked: </span> <span class="totalUnChecked"> Total Unchecked: </span> </div> </div>

And, here is the CSS for our grid:

.grid { display: grid; /* creates the grid */ grid-template-columns: repeat(2, max-content); /* creates two columns on the grid that are sized based on the content they contain */
} .total { grid-row: 1; /* places the counters on the first row */ grid-column: 1 / 3; /* ensures the counters span the full grid width, forcing other content below */
}

This is what we get as a result (with some additional styling):

See the Pen CSS Counter Grid by Preethi (@rpsthecoder) on CodePen.

See that? The counters are now located above the checkboxes!

We defined two columns on the grid element in the CSS, each accommodating its own content to their maximum size.

When we grid-ify an element, its contents (text including) block-ify, meaning they acquire a grid-level box (similar to block-level box) and are automatically placed in the available grid cells.

In the demo above, the counters take up both the grid cells in the first row as specified, and following that, every checkbox resides in the first column and the text after each checkbox stays in the last column.

The checkboxes are forced below the counters without changing the actual source order!

Since we didn’t change the source order, the counter works and we can see the running total count of checked and unchecked checkboxes at the top the same way we did when they were at the bottom. The functionality is left unaffected!

To be honest, there’s a staggering number of ways to code and implement a CSS Grid. You can use grid line numbers, named grid areas, among many other methods. The more you know about them, the easier it gets and the more useful they become. What we covered here is just the tip of the iceberg and you may find other approaches to create a grid that work equally well (or better).


Counting With CSS Counters and CSS Grid is a post from CSS-Tricks

Auto-Sizing Columns in CSS Grid: `auto-fill` vs `auto-fit`

One of the most powerful and convenient CSS Grid features is that, in addition to explicit column sizing, we have the option to repeat-to-fill columns in a Grid, and then auto-place items in them. More specifically, our ability to specify how many columns we want in the grid and then letting the browser handle the responsiveness of those columns for us, showing fewer columns on smaller viewport sizes, and more columns as the screen estate allows for more, without needing to write a single media query to dictate this responsive behavior.

We’re able to do that using just one line of CSS — the one-liner that reminds me of when Dumbledore just waved his wand in Horace’s apartment and “the furniture flew back to its original places; ornaments reformed in midair, feathers zoomed into their cushions; torn books repaired themselves as they landed upon their shelves…”.

This magical, media-query-less responsiveness is achieved using the repeat() function and the auto placement keywords.

Much has been written about this particular one-liner, so I won’t be elaborating on how it works. Tim Wright has a great writeup on this that I recommend reading.

To summarize, the repeat() function allows you to repeat columns as many times as needed. For example, if you’re creating a 12-columns grid, you could write the following one-liner:

.grid { display: grid; /* define the number of grid columns */ grid-template-columns: repeat(12, 1fr);
}

The 1fr is what tells the browser to distribute the space between the columns so that each column equally gets one fraction of that space. That is, they’re all fluid, equal-width columns. And the grid will, in this example, always have 12 columns regardless of how wide it is. This, as you have probably guessed, is not good enough, as the content will be too squished on smaller viewports.

So we need to start by specifying a minimum width for the columns, making sure they don’t get too narrow. We can do that using the minmax() function.

grid-template-columns: repeat( 12, minmax(250px, 1fr) );

But the way CSS Grid works, this will cause overflow in the row. The columns will not wrap into new rows if the viewport width is too narrow to fit them all with the new minimum width requirement, because we’re explicitly telling the browser to repeat the columns 12 times per row.

To achieve wrapping, we can use the auto-fit or auto-fill keywords.

grid-template-columns: repeat( auto-fit, minmax(250px, 1fr) );

These keywords tell the browser to handle the column sizing and element wrapping for us, so that the elements will wrap into rows when the width is not large enough to fit them in without any overflow. The fraction unit we used also ensures that, in case the width allows for a fraction of a column to fit but not a full column, that space will instead be distributed over the column or columns that already fit, making sure we aren’t left with any empty space at the end of the row.

At first glace of the names, it might seem like auto-fill and auto-fit are opposites. But in fact, the difference between is quite subtle.

Maybe it seems like you are getting extra space at the end of the column with auto-fit. But when and how?

Let’s take a look at what is really happening under the hood.

Fill or Fit? What’s the difference?

In a recent CSS workshop, I summarized the difference between auto-fill and auto-fit as follows:

auto-fill FILLS the row with as many columns as it can fit. So it creates implicit columns whenever a new column can fit, because it’s trying to FILL the row with as many columns as it can. The newly added columns can and may be empty, but they will still occupy a designated space in the row.

auto-fit FITS the CURRENTLY AVAILABLE columns into the space by expanding them so that they take up any available space. The browser does that after FILLING that extra space with extra columns (as with auto-fill ) and then collapsing the empty ones.

This may sound confusing at first, but it makes a lot more sense when you visualize this behavior. So we’ll be doing exactly that, with the Firefox DevTools’ Grid Inspector helping us visualize the size and position of our Grid items and columns.

Consider the following demo as an example.

See the Pen auto-fill vs auto-fit by Sara Soueidan (@SaraSoueidan) on CodePen.

The columns are defined using the repeat() function and have a minimum width of 100px, and a maximum set to 1fr , so that they would expand and equally share any extra space when it is available. As for the number of columns per row, we’re going to use the auto-placement keywords, so that we let the browser take care of the responsiveness of the grid and will wrap the columns into new rows when needed.

The browser will place and size the columns in the first example using the auto-fill keyword, and it will use auto-fit for the second.

.grid-container--fill { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
} .grid-container--fit { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

Up to a certain point, both auto-fill and auto-fit show identical results.

But they don’t have identical behavior under the hood. It just so happens that they will give the same result up to a certain viewport width.

The point at which these two keywords start exhibiting different behaviors depends on the number and size of columns defined in grid-template-columns, so it will differ from one example to another.

The difference between these two keywords is made apparent when the viewport gets wide enough to fit one (or more) extra column(s) (that) into the row. At that point, the browser is presented with two ways to handle the situation, and how it handles it largely depends on whether or not there is content to be placed into that extra column.

So, when the row can fit a new column, the browser goes like:

  1. “I have some space to fit a new column in there. Do I have any content (i.e. grid items) to go into that extra column? Yes? OK, all good. I’ll add the column into the row, and it will wrap into a new row on smaller viewports.”
  2. In the case where there is no content to place into a new column: “Do I allow this new column to occupy space in the row (and, therefore, affect the position and size of the rest of the rows)? or do I collapse that column and use its space to expand the other columns?”

auto-fill and auto-fit provide the answer to that last question in particular, and dictate how the browser should handle this scenario. To collapse or not to collapse, that is the question. And that is also the answer.
Whether you want it to collapse or not depends on your content, and how you want that content to behave in the context of a responsive design.

Let’s see how this works. To visualize the difference between auto-fill and auto-fit, take a look at the following screen recording. I’m resizing the viewport enough to create horizontal space that’s enough to fit one (or more) column(s) into the row. Remember that these two rows are identical, and have the exact same of content and column number. The only difference in this demo is that I’m using auto-fill for the first one and auto-fit for the second.

Notice what is happening there? If it’s still not clear, the following recording should make it clearer:

auto-fill behavior: “fill that row up! Add as many columns as you can. I don’t care if they’re empty — they should all still show up. If you have enough space to add a column, add it. I don’t care if it’s empty or not, it’s still occupying space in the row as if it were filled (as in: filled with content/grid items).”

While auto-fill fills the row with as many columns as it can, even if those columns are empty, auto-fit behaves a little differently.
auto-fit does, too, fill the row with more columns are the viewport width increases, but the only difference is that the newly added columns (and any column gaps associated with them) are collapsed. The Grid inspector is a fantastic way to visualize this. You’ll notice that columns are being added when you keep your eye on the Grid line numbers, which will increase as the viewport width increases.

auto-fit behavior: “make whatever columns you have fit into the available space. Expand them as much as you need to fit the row size. Empty columns must not occupy any space. Put that space to better use by expanding the filled (as in: filled with content/grid items) columns to fit the available row space.”

A useful tip to remember here is that the columns added in both cases (whether collapsed or not) are not implicit columns — that has specific meaning in the spec. In our case, we are adding/creating columns in the explicit grid in the same way as if we declared you wanted 12 columns, for example. So column number -1 will work to target the end of this grid, which it doesn’t if you are creating columns in the implicit grid. Props to Rachel Andrew for this tip.

Summing Up

The difference between auto-fill and auto-fit for sizing columns is only noticeable when the row is wide enough to fit more columns in it.

If you’re using auto-fit, the content will stretch to fill the entire row width. Whereas with auto-fill, the browser will allow empty columns to occupy space in the row like their non-empty neighbors — they will be allocated a fraction of the space even if they have no grid items in them, thus affecting the size/width of the latter.

Which behavior you want or prefer is completely up to you. I have yet to think of a use case where auto-fill would make more sense than auto-fit. Do you have any use cases? If you do, please feel free to share them in the comments below.


Auto-Sizing Columns in CSS Grid: `auto-fill` vs `auto-fit` is a post from CSS-Tricks

Five Design Fears to Vanquish With CSS Grid

CSS grid, along with a handful of other new CSS properties, are revolutionizing web design. Unfortunately, the industry hasn’t embraced that revolution yet and a lot of it is centered around fear that we can trace back to problems with the current state of CSS grid tutorials.

The majority of them fall into one of two categories:

  1. Re-creating classic web design patterns. Grid is great at replicating classic web design patterns like card grids and “holy grail” pages.
  2. Playing around. Grid is also great for creating fun things like Monopoly boards or video game interfaces.

These types of tutorials are important for new technology. They’re a starting point. Now is the time, as Jen Simmons says, to get out of our ruts. To do that, we must cast off our design fears.

Fear 1: Asymmetry

We’ve been trained in the era of frameworks that symmetric and orderly designs are better. It’s true that for many applications a symmetric design or an orderly grid of items is preferred. Yet, asymmetry has the ability to capture the eye and mind in a way that symmetry never will. Asymmetry is interesting in its disorder. If you’re nervous, you can always start small.

See the Pen Asymmetric Promo Grid by Bryan Robinson (@brob) on CodePen.

In this example, we have a simple promotional space. By using an asymmetric vertical and horizontal layout, we can make a stronger visual match between our icon and our button. This isn’t a large space, but it’s not afraid of using whitespace to draw the user’s eye where we want it to go.

Speaking of whitespace…

Fear 2: Negative Space

As we left the early 2000s, we decided it was OK if users had to scroll. We began introducing whitespace into our designs and most of this fell between rows of content. This made our designs much cleaner, but is vertical whitespace the only valid option?

In this example, the design incorporates negative space to create a sense of exploration through the page. By not using traditional content rows, the user’s eye is given a chance to scan and take things in at a slower pace.

See the Pen Experimental Homepage by Bryan Robinson (@brob) on CodePen.

Fear 3: Punk Rock?

There’s no shortage of design talks focused on the print layouts of the 1970s. It was a time of great stability in design tooling, which allowed creativity to bloom. With that came inspired and avant-garde design work that centered around the punk-rock scene.

So my question is this: Can we be punk rockers in web design?

In this example, the design doesn’t care about your preconceptions. Text overlap is a bug? Nope, it’s a feature. Images shouldn’t compete with each other? Survival of the fittest!

See the Pen Grid Overlap and Punk Rock Meditation by Bryan Robinson (@brob) on CodePen.

As this example asks, is this a good idea? It’s completely up for debate. What I know is this: our tools have matured and become more stable; now is the time for experimentation. Do we want the web to look the same year after year, or do we want to dream up new and exciting patterns?

Fear 4: New Sources of Inspiration

Sources of inspiration shouldn’t cause fear, but they do often cause headaches. Remember, inspiration doesn’t mean a 1:1 translation of a concept.

Punk rock graphic design

I mentioned earlier the amazing designs that came out of the ’70s and ’80s. Here are some links to continue researching punk-rock design:

  • The Art of Punk Posters by Sean O’Hagan
  • The Art of Chaos: Punk Rock’s Timeless Influence on Graphic Design by Simon Martin

Vintage movie graphic design

Studying film in college gave me a great appreciation for vintage movie graphic design. One of my professors once told me: “You should be able to tell the tone and subject of a film by its title cards.”

This is especially true of post-World War II films. Their title sequences and posters are a treasure trove of design ideas for setting a scene.

  • The Graphic Art of Film Title Design Throughout Cinema History by Rebecca Gross
  • Saul Bass on His Approach to Designing Movie Title Sequences by The Academy of Motion Picture Arts & Sciences

Learn how to create graphic design grids

Graphic designers have been using grids for layout for centuries, and there’s a lot of great literature on the creation of these grids:

  • Video: Mark Boulton | Designing Grids | CSS Day 2017
  • Guity Novin’s A History of Graphic Design: Chapter 58, History of Layout Design and Modern Newspapers and Magazines
  • Layout Essentials: 100 Design Principles for Using Grids by Beth Tondreau

Fear 5: Fallbacks

It’s true that Grid has only 74% support in the U.S. (at the time of this writing).

That should not stop you from pushing your designs forward. There are plenty of strategies for starting with support for all browsers and then pushing forward into new patterns.

  • Using CSS Grid: Supporting Browsers Without Grid by Rachel Andrew
  • Video: Progressing Our Layouts by Jen Simmons
  • Falling Forward — Rethinking Progressive Enhancement, Graceful Degradation and Developer Morality by Bryan Robinson

What’s next?

It falls to each of us to push our industry forward. The technology is in place to challenge ourselves to create new and interesting designs. This doesn’t have to be as pointed and intense as some of these examples. It starts by realizing we can do amazing things … or we can stagnate.

How will you push the industry forward?


Five Design Fears to Vanquish With CSS Grid is a post from CSS-Tricks

Calendar with CSS Grid

Here’s a nifty post by Jonathan Snook where he walks us through how to make a calendar interface with CSS Grid and there’s a lot of tricks in here that are worth digging into a little bit more, particularly where Jonathan uses grid-auto-flow: dense which will let Grid take the wheels of a design and try to fill up as much of the allotted space as possible.

As I was digging around, I found a post on Grid’s auto-placement algorithm by Ian Yates which kinda fleshes things out more succinctly. Might come in handy.

Oh, and we have an example of a Grid-based calendar in our ongoing collection of CSS Grid starter templates.

Direct Link to Article — Permalink


Calendar with CSS Grid is a post from CSS-Tricks