Front-end Design - Best Practices for CSS Grid Layout

An increasingly common question - now people are using CSS grid layouts for production - seems to be "what's the best practice?" The short answer to this question is to use the layout methods defined in the spec. The specific parts of the specification you choose to use, and how to combine grids with other layout methods like flexbox, play into the pattern you're trying to build and how you and your team want to work.

On a deeper level, I think this requirement for "best practices" may indicate a lack of confidence in using a very different layout approach than before. Maybe it's because we're using Grid for something it's not designed for, or maybe we should be using Grid. It could be a concern about supporting older browsers, or how the grid fits into our development workflow.

In this article, I'll try to cover a few things that might be described as best practices, and some things you might not need to worry about.

Best practices for front-end CSS grid layout

survey

To help understand this post, I'd like to know how other people use grid layout in production, what challenges do they face, and what do they really enjoy? Are there any common problems, problems or methods. To find out, I did a quick survey asking people how they use grid layouts, what they like most, and what challenges they find.

In the following article, I will quote and directly quote some of these responses. I'll also link to many other resources where you can find more about the techniques described. It turns out that there are plenty of interesting articles to unravel among the survey responses. I'll discuss some other things that come up in future posts.

Accessibility

If using any part of the grid specification, you need to be careful when using it, it's when using anything that might cause the content to reorder:

Authors must use commands and grid placement properties to achieve visual, illogical, reflow of content. Style sheets that use these features to perform logical reflow are inconsistent.

— Grid Specifications: Reordering and Accessibility

This is not unique to grids, however, the ability to rearrange content in two dimensions so easily makes it a bigger problem with grids. However, if using any method that allows content reordering -- be it Grid, Flexbox, or absolute positioning -- you need to be careful not to tie the visual experience to the structure of the content in the document. Screen readers (and people who only use the keyboard to navigate the document) will follow the order of the items in the source.

Where special care is required when using flex-direction to reverse the order in Flexbox; the order property in Flexbox or Grid; using any method to place grid items if it moves the items out of the logical order in the document; and using grid-auto -flow.

For more information on this issue, see the following resources:

  • Grid Layout and Accessibility - MDN

  • Flexbox disconnects from keyboard navigation

Which grid layout method should I use?

"With so many options in grids, it was a challenge to stick to a consistent way of writing gridlines (e.g. naming gridlines, defining grid template-regions, fallbacks, media queries) so it could be maintained across the team."

— Michelle Barker

When you first look at the grid, it can appear very difficult due to the different ways of creating a layout. Ultimately, however, it all comes down to where you go from one grid line to another. You can choose based on the layout you're trying to achieve, and what you're doing for your team and the site you're building.

There is no right or wrong way. Below, I'll discuss some common confusing topics. I have already mentioned many other potential confusions in previous articles. Grid and Barrier Blocks.”

Should I use implicit or explicit grid?

The grid grid-template-columns and grid-template-rows that you define are called explicit grids. Explicit grids allow you to name lines on the grid and also allow you to position the ends of the grid with the ends of the grid. You'll choose an explicit Grid to do these things, usually when you have a layout, all the layouts are designed and it's clear where your grid lines should go, and the size of the tracks .

I often use implicit grids to handle line tracking. I want to define the columns, but the rows will only autosize and expand to contain content. You can control the implicit grid to some extent. grid-auto-columns and grid-auto-rows However, you have less control than what you define.

You need to determine if you know how much content you have, so you can determine the number of rows and columns - in which case you can create an explicit grid. If you don't know how much content you have, but only need rows or columns to hold anything, you would use an implicit grid.

However, both approaches are possible. In the css below, I have defined three columns and three rows in an explicit grid, so the four row content will be as follows:

  • The tallest track, at least in height, but expanded to make the content taller,

  • A runway fixed at a height of 1 meter,

  • Orbital at least height (but extended).

Any further content goes into the rows created in the implicit grid, and I used the grid-auto-rows property to make these tracks at least 1,000 meters higher, expanding to auto.

.grid { display: grid; grid-template-columns: 1fr 3fr 1fr; grid-template-rows: minmax(200px auto) 400px minmax(300px, auto); grid-auto-rows: minmax(300px, auto); grid-gap: 20px; }Copy

Flexible grid with flexible number of columns

By using repeat symbols, autofill, and minmax, you can create as many audio tracks as a pattern that fits into the container, eliminating the need for media queries to some extent. This technique can be seen in this video tutorial and also in my recent article Responsive Design Based on Media Query 2018."

When you choose this technique, you are happy that the content is reduced below the previous content when there is less space, and is happy to allow a lot of flexibility in size. You have specified that you want to display your columns at the minimum size and will be filled automatically.

Several comments in the survey make me wonder if people choose this approach when they really want a grid with a fixed number of columns. If you end up with an unpredictable number of columns at some breakpoints, you're better off setting the number of columns - and redefining it as needed, rather than using auto-fill or auto-fit.

  • We developed responsive layouts

  • Free data-driven application

Which orbital sizing method should I use?

I describe tracking dimensions in detail in the article. How big is that box? Amount of Understanding in Grid Layout However, I often get asked how and which method to use. In particular, I was asked about percentage sizes and fr units. If you're only using fr units as child elements, it's different than using percentages because it allocates free space. If you put a larger item on a track, fr till will work to make that track take up more space and allocate what is left over.

.grid { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 20px;}Copy

Best practices for front-end CSS grid layout

The first column is wider because the grid has more space allocated.

To make fr units distribute space in a full grid container, you need to give it a minimum size of 0 using minmax().

.grid { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr) minmax(0,1fr); grid-gap: 20px;}Copy

Best practices for front-end CSS grid layout

Forcing a minimum value of 0 may cause overflow.

So you can choose to use fr in either of these scenarios: you want to allocate space allocations from automatic (the default behavior) and those that require equal distribution. I usually use fr units, then it makes the size for you and allows for fixed width tracks or gaps. The only time I use percentages is when I add a grid component to an existing layout that uses other layout methods. If I want my grid components to align with float or flex based layouts that use percentages, using them in my grid layout means that everything uses the same sizing method.

Automatically place items or set their position?

You will often find that you only need to place one or two items in the layout, and the rest are set according to content order. In fact, it's a very good test that you didn't disconnect the source and visualize it. If things are pretty much all based on automatic placement, they're probably in good order.

Once I've decided where everything is going, I tend to assign a place to everything. This means that if someone adds something to the document, the grid automatically places it in some unexpected place, so it doesn't happen to me because weird things happen. If everything is placed, the grid will place the item in the next available empty grid cell. It's probably not where you want it to be, but it's probably better to sit at the end of your layout than go into something in the middle and push something else.

Which positioning method to use?

When using grid layout, ultimately everything boils down to placing items from one row to another. Everything else is essentially a helper in this regard.

If you want to name the row, choose your team, use the grid template area, or you'll use a combination of different types of layouts. I find that I like to use the grid template area to use widgets in particular. However, there is no right or wrong. Find out what works best for you.

Grid combined with other layout mechanisms

Keep in mind that grid layout is not really a layout method to manage them all, it is designed to be a layout of some kind - i.e. a 2D layout. Other layout methods still exist, you should consider each pattern and fit it best.

I think it's been very difficult for us because we used to hack with layout methods to get them to do things they weren't really designed for. Now is a good time to take a step forward and look at the layout methods for the tasks they designed, and remember to use them to accomplish those tasks.

Especially no matter how often I write about grids and flexbox, I ask which one should be used. There are a lot of patterns that make perfect sense no matter the layout method, it's really up to you. No one will yell at you because you chose grid, or grid on flexbox.

In my own work, I tend to implement components using Flexbox because I want the natural size of items to strongly control their layout, basically pushing other items around. I also use flexbox a lot because I want alignment, since the box alignment property is only used in flexbox and grid. I may have a flex container with one child in order to allow me to make adjustments to that child.

May be the sign of Flexbox is not the layout method I should choose, that's when I start adding percentage widths and settings to flex items. flex-grow
to 0. The reason for increasing the percentage width to flex items is often because I'm trying to linearize them in two dimensions (building things in two dimensions is exactly what a grid needs). Try both, though, and see which looks best for the content or design pattern. You're unlikely to have any problems by doing this.

Nested grids and flex items

This also generates a lot and has no problem creating grid items, so does the grid container, so nesting a grid within another grid. You can do the same in Flexbox, creating a flex item and flex container. You can also create grid items and flex containers or a grid container flex item - none of that is a problem!

What we can't do at the moment is nest a grid, and the nested grid tracks using the grid defined in the parent. This would be very useful and most useful to suggest that level 2 of the grid specification hopefully resolves. The nested grid is now a new grid, so you'll need to resize it carefully to make sure it aligns with any parent tracks.

You can have many grids on one page

Several comments came up in the survey, and to my surprise there seemed to be an idea that grids should be limited to the main layout, and that many grids on one page might not be a good thing. You can have as many grids as you like! Use grids for big things and small things, and if it makes sense to grids, then use grids.

Support for old browsers and Support for old browsers

"The grid used with @support gives us more control over the amount of layout changes we expect to see. It also works very well with our progressive enhancement approach, meaning we can reward those with modern browsers that don't allow A way for those who don't use the latest technology to deliver content.

— Joe Lambert at work n.rareloop.com

In the survey, many people mentioned older browsers, however, there was a fairly equal split between those who felt that supporting older browsers was difficult, and those who felt relieved due to feature queries and grids overriding other layout methods. I've written a bit about the rationale behind creating these fallbacks. Use css grid: no grid support browser."

In general, modern browsers are more interoperable than their predecessors. We usually see less actual "browser bugs", if you use html and css correctly then you will often find that what you see in a browser is the same as in another browser.

Of course, we do have a situation where browsers don't yet provide support for a spec or some part of the spec. With the evolution of grids, we are very fortunate that browsers send grid layouts to each other in a very short time in a very complete and interoperable way. As a result, our testing considerations tend to require testing browsers with grids, without grids. You can also choose to use -msthe prefix version in IE10 and IE11 and then ask to test as a third type of browser.

Browsers that support modern grid layouts (but not the IE version) also support feature queries. This means that you can test grid support before using it.

Test for browsers that don't support grids

Use fallbacks for browsers that don't support grid layouts (or use -ms for prefixed versions of IE10 and 11, you'll want to test how those browsers render grid layouts. To do this, you'll need a kind of method to view the site in the sample browser.

I wouldn't break your function query by checking if something ridiculous is supported, or a misspelled value. grid
. This approach will only work if the stylesheet is very simple, and you can totally combine everything with your grid layout in a feature query. This is a very fragile and time-consuming way of working, especially if you use grids extensively. Also, an older browser not only lacks support for grid layouts, but also other css properties. If you're looking for "best practices" then set yourself up so you can test your work in a good position to be high above!

There are a few easy ways to set up a proper way to test your fallbacks. The easiest way - if you have a reasonably fast internet connection and don't mind paying a subscription fee - is to use a service like BrowserStack. It's a service that makes a website (even a website developed on a computer) viewable across a real browser. BrowserStack does offer free accounts for open source projects.

Best practices for front-end CSS grid layout

To test locally, my recommendation is to use a virtual machine with the target browser installed. Microsoft offers a free service. The virtual machine download brings the ie version back to ie8, and edge. You can also install to a virtual machine, an older version of the browser that doesn't have grid support at all. For example, get a copy of firefox 51 or below. After installing your old firefox, make sure to turn off automatic updates as explained here or it will silently update itself!

Then you can test your site in IE11 and then on a vm for non-firefox support (less brittle solution than misspelled values). It might take you an hour or so to set up, but you'll be testing your self-assessment in a really good place.

unlearning old habits

"This is the first time I've used grid layout, so there are a lot of concepts to learn, properties to understand. Conceptually, I found the hardest thing to forget about all the things I've done over the years, like cleaning up floats, Pack everything in a container.

– HiddeWorks hiddendevries.nl/en

Many people who responded to the survey mentioned that old habits need to be broken, and how to learn layouts more easily is easier for completely new CSS. I tend to agree. When people teach people, beginners have few problems with grids, while experienced developers struggle to return grids to a one-dimensional layout approach. I've seen attempts at "grid systems" using CSS grids, which would return the row wrappers needed for floating or flex based grids.

Don't be afraid to try new technologies. If you have the ability to test in a few browsers and keep an eye out for potential accessibility issues, you really can't go wrong. If you find a great way to create a pattern, let other people know about it. We're all new to producing new products using grids, so there's definitely a lot to discover and share.

"Grid layout is the most exciting CSS development since media queries. It's a really good idea for real world developers and it's an absolute joy to use in production - for designers and developers all the same.

– try trying to work n.trysmudford.com

For wrapping, here's a very short list of current best practices! If you find things that do or don't work in your own situation, then please add them to the comments.

  1. Be very aware of the possibility of content reordering. Check that you are not disconnecting the visualization from the document order.

  2. Test with an actual target browser using a local or remote virtual machine.

  3. Don't forget that the old layout methods are still valid and useful. Try different ways to implement the pattern. Don't get hung up on having to use Grid.

  4. Know that, as an experienced front-end developer, you probably have a whole preconceived idea of ​​how layouts work. Try to revisit these new approaches instead of forcing them back to old patterns.

  5. Keep trying. We are all new here. Test your work and share what you find.

Follow the editor to learn more exciting content, and you can also privately message "Learn" to receive high-quality front-end free learning course videos. At the same time, I will share high-quality materials for you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325099838&siteId=291194637