Performant Expandable Animations: Building Keyframes on the Fly

Animations have come a long way, continuously providing developers with better tools. CSS Animations, in particular, have defined the ground floor to solve the majority of uses cases. However, there are some animations that require a little bit more work.

You probably know that animations should run on the composite layer. (I won’t extend myself here, but if you want to know more, check this article.) That means animating transform or opacity properties that don’t trigger layout or paint layers. Animating properties like height and width is a big no-no, as they trigger those layers, which force the browser to recalculate styles.

On top of that, even when animating transform properties, if you want to truly hit 60 FPS animations, you probably should get a little help from JavaScript, using the FLIP technique for extra smoother animations! 

However, the problem of using transform for expandable animations is that the scale function isn’t exactly the same as animating width/height properties. It creates a skewed effect on the content, as all elements get stretched (when scaling up) or squeezed (when scaling down).

So, because of that, my go-to solution has been (and probably still is, for reasons I will detail later), technique #3 from Brandon Smith’s article. This still has a transition on height, but uses Javascript to calculate the content size, and force a transition using requestAnimationFrame. At OutSystems, we actually used this to build the animation for the OutSystems UI Accordion Pattern.

Generating keyframes with JavaScript

Recently, I stumbled on another great article from Paul Lewis, that details a new solution for expanding and collapsing animations, which motivated me to write this article and spread this technique around.

Using his words, the main idea consists of generating dynamic keyframes, stepping…

[…] from 0 to 100 and calculate what scale values would be needed for the element and its contents. These can then be boiled down to a string, which can be injected into the page as a style element. 

To achieve this, there are three main steps.

Step 1: Calculate the start and end states

We need to calculate the correct scale value for both states. That means we use getBoundingClientRect() on the element that will serve as a proxy for the start state, and divide it with the value from the end state. It should be something like this:

function calculateStartScale () {   const start= startElement.getBoundingClientRect();   const end= endElement.getBoundingClientRect();   return {     x: start.width / end.width,     y: start.height / end.height   }; }

Step 2: Generate the Keyframes

Now, we need to run a for loop, using the number of frames needed as the length. (It shouldn’t really be less than 60 to ensure a smooth animation.) Then, in each iteration, we calculate the correct easing value, using an ease function:

function ease (v, pow=4) {   return 1 - Math.pow(1 - v, pow); }  let easedStep = ease(i / frame);

With that value, we’ll get the scale of the element on the current step, using the following math:

const xScale = x + (1 - x) * easedStep; const yScale = y + (1 - y) * easedStep;

And then we add the step to the animation string:

animation += `$ {step}% {   transform: scale($ {xScale}, $ {yScale}); }`;

To avoid the content to get stretched/ skewed, we should perform a counter animation on it, using the inverted values:

const invXScale = 1 / xScale; const invYScale = 1 / yScale;  inverseAnimation += `$ {step}% {   transform: scale($ {invXScale}, $ {invYScale}); }`;

Finally, we can return the completed animations, or directly inject them in a newly created style tag.

Step 3: Enable the CSS animations 

On the CSS side of things, we need to enable the animations on the correct elements:

.element--expanded {   animation-name: animation;   animation-duration: 300ms;   animation-timing-function: step-end; }  .element-contents--expanded {   animation-name: inverseAnimation ;   animation-duration: 300ms;   animation-timing-function: step-end; }

You can check the example of a Menu from Paul Lewis article, on Codepen (courtesy of Chris Coyer):

Building an expandable section 

After grasping these baseline concepts, I wanted to check if I could apply this technique to a different use case, like a expandable section.

We only need to animate the height in this case, specifically on the function to calculate scales. We’re getting the Y value from the section title, to serve as the collapsed state, and the whole section to represent the expanded state:

    _calculateScales () {       var collapsed = this._sectionItemTitle.getBoundingClientRect();       var expanded = this._section.getBoundingClientRect();              // create css variable with collapsed height, to apply on the wrapper       this._sectionWrapper.style.setProperty('--title-height', collapsed.height + 'px');        this._collapsed = {         y: collapsed.height / expanded.height       }     }

Since we want the expanded section to have absolute positioning (in order to avoid it taking space when in a collapsed state), we are setting the CSS variable for it with the collapsed height, applied on the wrapper. That will be the only element with relative positioning.

Next comes the function to create the keyframes: _createEaseAnimations(). This doesn’t differ much from what was explained above. For this use case, we actually need to create four animations:

  1. The animation to expand the wrapper
  2. The counter-expand animation on the content
  3. The animation to collapse the wrapper
  4. The counter-collapse animation on the content

We follow the same approach as before, running a for loop with a length of 60 (to get a smooth 60 FPS animation), and create a keyframe percentage, based on the eased step. Then, we push it to the final animations strings:

outerAnimation.push(`   $ {percentage}% {     transform: scaleY($ {yScale});   }`);    innerAnimation.push(`   $ {percentage}% {     transform: scaleY($ {invScaleY});   }`);

We start by creating a style tag to hold the finished animations. As this is built as a constructor, to be able to easily add multiple patterns, we want to have all these generated animations on the same stylesheet. So, first, we validate if the element exists. If not, we create it and add a meaningful class name. Otherwise, you would end up with a stylesheet for each section expandable, which is not ideal.

 var sectionEase = document.querySelector('.section-animations');  if (!sectionEase) {   sectionEase = document.createElement('style');   sectionEase.classList.add('section-animations');  }

Speaking of that, you may already be wondering, “Hmm, if we have multiple expandable sections, wouldn’t they still be using the same-named animation, with possibly wrong values for their content?” 

You’re absolutely right! So, to prevent that, we are also generating dynamic animation names. Cool, right?

We make use of the index passed to the constructor from the for loop when making the querySelectorAll('.section') to add a unique element to the name:

var sectionExpandAnimationName = "sectionExpandAnimation" + index; var sectionExpandContentsAnimationName = "sectionExpandContentsAnimation" + index;

Then we use this name to set a CSS variable on the current expandable section. As this variable is only in this scope, we just need to set the animation to the new variable in the CSS, and each pattern will get its respective animation-name value.

.section.is--expanded {   animation-name: var(--sectionExpandAnimation); }  .is--expanded .section-item {   animation-name: var(--sectionExpandContentsAnimation); }  .section.is--collapsed {   animation-name: var(--sectionCollapseAnimation); }  .is--collapsed .section-item {   animation-name: var(--sectionCollapseContentsAnimation); }

The rest of the script is related to adding event listeners, functions to toggle the collapse/expand status and some accessibility improvements.

About the HTML and CSS: it needs a little bit of extra work to make the expandable functionality work. We need an extra wrapper to be the relative element that doesn’t animate. The expandable children have an absolute position so that they don’t occupy space when collapsed.

Remember, since we need to make counter animations, we make it scale full size in order to avoid a skew effect on the content.

.section-item-wrapper {   min-height: var(--title-height);   position: relative; }  .section {   animation-duration: 300ms;   animation-timing-function: step-end;   contain: content;   left: 0;   position: absolute;   top: 0;   transform-origin: top left;   will-change: transform; }  .section-item {   animation-duration: 300ms;   animation-timing-function: step-end;   contain: content;   transform-origin: top left;   will-change: transform;   }

I would like to highlight the importance of the animation-timing-functionproperty. It should be set to linear or step-end to avoid easing between each keyframe.

The will-change property — as you probably know — will enable GPU acceleration for the transform animation for an even smoother experience. And using the contains property, with a value of contents, will help the browser treat the element independently from the rest of the DOM tree, limiting the area before it recalculates the layout, style, paint and size properties.

We use visibility and opacity to hide the content, and stop screen readers to access it, when collapsed.

.section-item-content {   opacity: 1;   transition: opacity 500ms ease; }  .is--collapsed .section-item-content {   opacity: 0;   visibility: hidden; }

And finally, we have our section expandable! Here’s the complete code and demo for you to check:

Performance check

Anytime we work with animations, performance ought to be in the back of our mind. So, let’s use developer tools to check if all this work was worthy, performance-wise. Using the Performance tab (I’m using Chrome DevTools), we can analyze the FPS and the CPU usage, during the animations.

And the results are great!

The higher the green bar, the higher the frames. And there’s no junk either, which would be signed by red sections.

Using the FPS meter tool to check the values at greater detail, we can see that it constantly hits the 60 FPS mark, even with abusive usage.

Final considerations

So, what’s the verdict? Does this replace all other methods? Is this the “Holy Grail” solution?

In my opinion, no. 

But… that’s OK, really! It’s another solution on the list. And, as is true with any other method, it should be analyzed if it’s the best approach for the use-case.

This technique definitely has its merits. As Paul Lewis says, this does take a lot of work to prepare. But, on the flip side, we only need to do it once, when the page loads. During interactions, we are merely toggling classes (and attributes in some cases, for accessibility).

However, this brings some limitations for the UI of the elements. As you could see for the expandable section element, the counter-scale makes it much more reliable for absolute and off-canvas elements, like floating-actions or menus. It’s also difficult to styled borders because it’s using overflow: hidden.

Nevertheless, I think there’s tons of potential with this approach. Let me know what you think!

The post Performant Expandable Animations: Building Keyframes on the Fly appeared first on CSS-Tricks.

CSS-Tricks

, , , ,

Max Stoiber’s Strong Opinion About Margins

Going with that title instead of the classic developer clickbait version Max used. 😉

We should ban margin from our components.

Don’t use margin?! This thing I’ve been doing my entire career and don’t have any particular problems with?!

Well, that’s not exactly Max’s point. The point is that any particular component doesn’t necessarily know what context it is in, so it also doesn’t know what kind of spacing is necessary around it. His solution? Leave it to a parent component.

I don’t have any particular problem with that. Then again, constructing things can sometimes feel overwhelming when you’ve got a route component wrapping a query component wrapping a styled component wrapping a state machine component wrapping a spacer component wrapping some kind of semantic template. If that sounds like a lot, I bet a lot of y’all’s JavaScript-built codebases nest much deeper than that already.

In this world of component-driven front-ends, we need to make sure we don’t end up with such thick soup we can’t reason through it.

This also reminds me of a bold prediction from Adam Argyle, that the use of margin will decline entirely as gap is used more heavily in all-flexbox-and-grid situations.

Direct Link to ArticlePermalink

The post Max Stoiber’s Strong Opinion About Margins appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

How to build a bad design system

I didn’t realize this until it was far too late, but one of the biggest mistakes that’s made on a design systems team is a common mismanagement issue: there are too many people in a meeting and they have too many dang opinions.

Is there a conversation about the color of your buttons that’s taking place? Great! Everyone needs a consistent set of colors so that users know what to click and so that designers don’t have to choose from a smorgasbord of options. But the tough question at the beginning isn’t what colors we should choose and when to pick them, but rather this: how many people are in that dang room?

How many people are making decisions about your design system?

Are three people talking about the buttons in your design system? Wonderful. Are there 20? Woof! That’s a serious problem because it shows that far too much energy is being spent on the wrong things; it’s nothing short of mismanagement, in fact.

(This is why I reckon design systems aren’t about design or even about systems. It’s actually about managing people and their time, attention, and focus. But that’s a rant for another day.)

Anyway, the hard call that someone on a large design team will have to make at some point or another is deciding which people need to leave the room. And that sounds really mean, I get it, but it’s the kind thing to do. If everyone has opinions then, first, nothing will get done and, second, you’ll end up causing rifts when some opinions are shunned and others are heard.

It was thoroughly shocking to me when I started my first big design systems project that the more people that joined any given meeting, the less effective we were. It was like the IQ of the room dropped by ten thousand points. And I was also shocked that the hardest problem wasn’t about building the system; learning about TypeScript, making sure components were accessible, doing audits, etc. Instead it was this: the whole too-many-people-in-a-meeting thing.

Everyone cannot possibly be allowed to voice their opinions about every tiny detail of the UI and at some point someone needs to come in and draw a line as to who is allowed to care about what things. That’s not to say that people aren’t allowed to have feedback — feedback should always be welcome! — but one of the main advantages of having a design systems team is to offset all those decisions onto someone else.

I was listening to this livestream of Jason Fried and DHH the other day and they mention that:

If you want to be even less sure about something, all you have to do is ask one more person what their take is.

That’s definitely the feeling I had when too many people were talking about buttons or borders or anything, really. This sort of hopeless feeling that change just isn’t possible. And that you can’t make a decision about something because you need to massage the egos of everyone in the room.

This also reminds me of this great post by Paul Ford about what the web is:

“Why wasn’t I consulted,” which I abbreviate as WWIC, is the fundamental question of the web. It is the rule from which other rules are derived. Humans have a fundamental need to be consulted, engaged, to exercise their knowledge (and thus power), and no other medium that came before has been able to tap into that as effectively.

Working in a big organization is shocking to newcomers because of this, as suddenly everyone has to be consulted to make the smallest decision. And the more people you have to consult to get something done, the more bureaucracy exists within that company. In short: design systems cannot be effective in bureaucratic organizations. Trust me, I’ve tried.


Anyway, the way to fight that is by drawing that line, by kicking people out of meetings that don’t need to be there. It’s really the kindest thing to do because it will make your design system much faster to build, and less stressful for you.

The post How to build a bad design system appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Wide Gamut Color in CSS with Display-P3

Here’s something I’d never heard of before: Display-P3 support in CSS Color Module Level 4 spec. This is a new color profile supported by certain displays and it introduces a much wider range of colors that we can choose from.

Right now the syntax looks something like this in CSS:

header {   color: rgb(0, 255, 0); /* fallback color */   color: color(display-p3 0 1 0); }

It looks weird, huh? Over on the WebKit blog, Nikita Vasilyev shows how we can see these new colors in Safari’s DevTools:

Back in 2016, Dean Jackson wrote about improving color on the web and why Apple is interested in this much wider color gamut. The general idea is that more accurate colors make for a better and more vibrant user experience.

Also, it looks like all this is only available in Safari right now.

Direct Link to ArticlePermalink

The post Wide Gamut Color in CSS with Display-P3 appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

APIs and Authentication on the Jamstack

The first “A” in the Jamstack stands for “APIs” and is a key contributor to what makes working with static sites so powerful. APIs give developers the freedom to offload complexity and provide avenues for including dynamic functionality to an otherwise static site. Often, accessing an API requires validating the authenticity of a request. This frequently manifests in the form of authentication (auth) and can be done either client side or server side depending on the service used and the task being accomplished. 

Given the vast spectrum of protocols available, APIs differ in their individual auth implementations. These auth protocols and implementation intricacies add an additional challenge when integrating APIs into a Jamstack site. Thankfully, there is a method to this madness. Every protocol can be mapped to a specific use case and implementing auth is a matter of understanding this.

To illustrate this best, let’s dive into the various protocols and the scenarios that they’re best suited for.

Summon the protocols

OAuth 2.0 is the general standard by which authentication today follows. OAuth is a fairly flexible authorization framework that constitutes a series of grants defining the relationship between a client and an API endpoint. In an OAuth flow, a client application requests an access token from an authorization endpoint and uses that to sign a request to an API endpoint.

There are four main grant types — authorization code, implicit flow, resource owner credential, and client credentials. We’ll look at each one individually.

Authorization Code Grant 

Of all OAuth grant types, the Authorization Code Grant is likely the most common one. Primarily used to obtain an access token to authorize API requests after a user explicitly grants permission, this grant flow follows a two-step process.

  • First, the user is directed to a consent screen aka the authorization server where they grant the service restricted access to their personal account and data.
  • Once permission has been granted, the next step is to retrieve an access token from the authentication server which can then be used to authenticate the request to the API endpoint.

Compared to other grant types, the Authorization Code Grant has an extra layer of security with the added step of asking a user for explicit authorization. This multi-step code exchange means that the access token is never exposed and is always sent via a secure backchannel between an application and auth server. In this way, attackers can’t easily steal an access token by intercepting a request. Google-owned services, like Gmail and Google Calendar, utilize this authorization code flow to access personal content from a user’s account. If you’d like to dig into this workflow more, check out this blog post to learn more.

Implicit Grant

The Implicit Grant is akin to the Authorization Code Grant with a noticeable difference: instead of having a user grant permission to retrieve an authorization code that is then exchanged for an access token, an access token is returned immediately via the the fragment (hash) part of the redirect URL (a.k.a. the front channel).

With the reduced step of an authorization code, the Implicit Grant flow carries the risk of exposing tokens. The token, by virtue of being embedded directly into the URL (and logged to the browser history), is easily accessible if the redirect is ever intercepted.

Despite its vulnerabilities, the Implicit Grant can be useful for user-agent-based clients like Single Page Applications. Since both application code and storage is easily accessed in client-side rendered applications, there is no safe way to keep client secrets secure. The implicit flow is the logical workaround to this by providing applications a quick and easy way to authenticate a user on the client side. It is also a valid means to navigate CORS issues, especially when using a third-party auth server that doesn’t support cross-origin requests. Because of the inherent risks of exposed tokens with this approach, it’s important to note that access tokens in Implicit Flow tend to be short-lived and refresh tokens are never issued. As a result, this flow may require logging in for every request to a privileged resource.

Resource Owner Credential

In the case of the Resource Owner Credential Grant, resource owners send their username and password credentials to the auth server, which then sends back an access token with an optional refresh token. Since resource owner credentials are visible in the auth exchange between client application and authorization server, a trust relationship must exist between resource owner and client application. Though evidently less secure than other grant types, the Resource Owner Credential grant yields an excellent user experience for first party clients. This grant flow is most suitable in cases where the application is highly privileged or when working within a device’s operating system. This authorization flow is often used when other flows are not viable.

Client Credential

The Client Credentials Grant type is used primarily when clients need to obtain an access token outside of the context of a user. This is suitable for machine to machine authentication when a user’s explicit permission cannot be guaranteed for every access to a protected resource. CLIs, and services running in the back end are instances when this grant type comes in handy. Instead of relying on user login, a Client ID and Secret are passed along to obtain a token which can then be used to authenticate an API request.

Typically, in the Client Credential grant, a service account is established through which the application operates and makes API calls. This way, users are not directly involved and applications can still continue to authenticate requests. This workflow is fairly common in situations where applications want access to their own data, e.g. Analytics, rather than to specific user data.

Conclusion

With its reliance on third party services for complex functionality, a well-architected authentication solution is crucial to maintain the security of Jamstack sites. APIs, being the predominant way to exchange data in the Jamstack, are a big part of that. We looked at four different methods for authenticating API requests, each with its benefits and impacts on user experience.

We mentioned at the start that these four are the main forms of authentication that are used to request data from an API. There are plenty of other types as well, which are nicely outlined on oauth.net. The website as a whole is an excellent deep-dive on not only the auth types available, but the OAuth framework as a whole.

Do you prefer one method over another? Do you have an example in use you can point to? Share in the comments!

The post APIs and Authentication on the Jamstack appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

How to secure a website and be foolproof against surprises

[Top]

RSS Stuff

Laura Kalbag wrote How to read RSS in 2020. This would be a nice place to send someone curious about RSS: what it is, what it’s for, and how you can start using it as a reader. I like this callout, too:

Sometimes the content is just an excerpt, encouraging you to read the rest of the content on the original site. I think this defeats the point of providing RSS, where a big benefit is that the reader can customise how the posts display in their feed reader to improve their reading experience.

I absolutely love Khoi Vinh’s writing, but have long been surprised that his feed is truncated. Barely even excerpts. WHY KHOI WHY?!

Laura linked up lire as a reader, and I’d never seen that one before. It’s apparently got good screenreader support.

Louis Lazaris wrote Front-end RSS Feeds (2020 Edition). It has OPML files that are in big groups of feeds that you’ll be subscribed to once their imported into a feed reader (some have that as an option). There is also just a big list too.

Louis likes NewsBlur.

I’m still on my Feedbin + NetNewsWire kick. NetNewsWire for iOS just dropped as well. I installed it and like it OK so far, but I think I still prefer Reeder on iOS which also syncs with Feedbin nicely.

I haven’t had a chance to play with Unread 2 yet for iOS, but I love the idea that it “automatically determines which feeds contain only article summaries” and goes and fetches the rest of the content from the site for you.

The post RSS Stuff appeared first on CSS-Tricks.

CSS-Tricks

[Top]

gqless

This is so cool. I mean, GraphQL is already cool. It’s very satisfying to write an understandable-looking query for whatever you want and then use that data in templates.

But what if you didn’t have to write the query at all? What if you just wrote the templates pretending you already had the data, and the query built itself? I haven’t even tried this project yet but it feels like how things should be.

Reminds me of how Perch CMS doesn’t ask you to model data up front. You build page templates, and the CMS creates data entry pages based on the data you need in the template.

Direct Link to ArticlePermalink

The post gqless appeared first on CSS-Tricks.

CSS-Tricks

[Top]

How They Fit Together: Transform, Translate, Rotate, Scale, and Offset

Firefox 72 was first out of the gate with “independent transforms.” That is, instead of having to combine transforms together, like:

.el {   transform: rotate(10deg) scale(0.95) translate(10px, 10px); }

…we can do:

.el {   rotate: 10deg;   scale: 0.95;   translate: 10px 10px; }

That’s extremely useful, as having to repeat other transforms when you change a single one, lest remove them, is tedious and prone to error.

But there is some nuance to know about here, and Dan Wilson digs in.

Little things to know:

  • Independent transforms happen first. So, if you also use a transform, that can override them if the same transform types is used.
  • They all share the same transform-origin.
  • The offset-* properties also effectively moves/rotates elements. Those happen after independent transforms and before transform.

Direct Link to ArticlePermalink

The post How They Fit Together: Transform, Translate, Rotate, Scale, and Offset appeared first on CSS-Tricks.

CSS-Tricks

, , , , , ,
[Top]

4 CSS Grid Properties (and One Value) for Most of Your Layout Needs

CSS Grid provides us with a powerful layout system for websites. The CSS-Tricks guide gives you a comprehensive overview of Grid’s properties with layout examples. What we’re going to do here is a reverse approach to show you the smallest possible set of grid properties you need to know to meet most of your layout needs.

These five properties will get you up and running:

  • display (for the grid value)
  • grid-template-columns
  • grid-gap
  • grid-auto-flow
  • grid-column / grid-row

Here’s how simple it is. Let’s assume you want to implement the following layout for small, medium and large screens.

Small and medium-sized screens
Large screen layout

This is the markup we’ll be working with:

 <!-- Stuff before -->  <nav class="container-nav">   <ul>     <li></li>     <li></li>     <li></li>     <li></li>     <li></li>     <li></li>     <li></li>     <li></li>     <li></li>   </ul> </nav>  <div class="container-main">   <section class="item item-type-a"></section>   <section class="item item-type-b"></section>   <section class="item item-type-b"></section>   <section class="item container-inner">     <section class="item-inner"></section>     <section class="item-inner"></section>     <section class="item-inner"></section>     <section class="item-inner"></section>     <section class="item-inner"></section>   </section> </div>  <!-- Stuff after -->

If we apply a few baseline styles, this is what we get, which is already sufficient for small screens:

Now we can get into the grid properties!

Use display: grid to divide the page into independent layout containers

First, we need to determine which parts of the page should be aligned with grid layouts. It is possible to define a single grid layout for the whole page. However, for websites with a very complex structure (e.g. news websites), handling a large grid quickly becomes complicated to wrangle. In this case, I recommend breaking things down into several, independent grid containers.

Like this:

Where do you draw the line between what is and isn’t a grid? Here’s a personal rule of thumb I follow:

If the layout in a particular part of the page does not fit into the grid of an adjacent or surrounding part of the page, make that part its own grid container.

I have drawn the grid lines into the page section with the class .container-main in the following image You may notice that the section with the .container-inner class from the markup does not fit exactly into the grid of rows.

Here’s another possible layout where the small sections fit into the surrounding grid if a finer line raster is chosen. A separate grid container is not absolutely necessary here.

To kick this off, let’s .container-main into a grid container. This is the basic building block for CSS Grid — turning an element into a grid container with the display property:

.container-main {   display: grid;          }

We’ll want to do the same with our other grid containers:

.container-inner {   display: grid;          }  .container-nav {   display: grid;          }

Use grid-template-columns to define the required columns

Next, we’re going to define the number of columns we need in each grid container and how wide those columns should be. My guideline for the number of columns:  use the smallest common multiple of the maximum number of columns required for the different screen sizes.

How does that work? The .container-main element has a total of two columns on medium-sized screens. If we take that and multiply it by the number of columns on large screens (three), we get a total of six columns.

We can do the same for our navigation, the .container-inner element. There are three columns on medium-sized screens, which we multiple by one column on large screens to get a total of three columns.

The .container-nav element provides no number of columns. In this case, the grid system should automatically adjust the number of columns to the number of menu elements. It’s common to add or remove items in a navigation, and it’d be great if it responded accordingly, which is something grid can help us with a little later on.

OK, so we defined the number of columns for each grid container. Let’s use the grid-template-columns property to set those into place. But, first a couple of minor details:

  • The grid-template-columns property is only used on the grid container. In other words, you won’t find it being used (at least correctly) on a grid item inside the container.
  • The property accepts a bunch of different values that both define the number of columns and how wide they should be. The one we’re interested in here is the fractional (fr) unit. I’d highly suggest checking out Robin’s overview because it’s unique to grid and does an amazing job doing calculations to decide how grid elements fit inside a grid container.

We need six equal-width columns in .container-main. We can write that like this:

.container-main {   display: grid;   grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr; }

Or, we can turn to the repeat() function to simplify it into something more readable:

.container-main {   display: grid;   grid-template-columns: repeat(6, 1fr); }

Let’s take that knowledge and apply it to our .container-inner element as well, which we decided needs three columns.

.container-inner {   display: grid;   grid-template-columns: repeat(3, 1fr); }

Use grid-gap to add spacing between grid items

By default, grid uses all the space it has in a grid container to fit in grid items. Having elements flush next to one another might be a design requirement, but not for the particular layout we’re making. We want some breathing room between things!

We have the grid-gap property for that. Again, this is a property that’s just for grid containers and what it does is create vertical and horizontal spacing between grid items. It’s actually a shorthand property that combines the vertical spacing powers of grid-row-gap and horizontal spacing powers of grid-column-gap. It’s handy that we’re able to break things out like that but, in times like this where we’re working with the same amount of spacing in each direction, the shorthand grid-gap is much nicer to write.

We want 20px of space between grid items in .container-main, 10px of space in .container-inner, and 5px of space in .container-nav. No problem! All it takes is a one-liner on each grid container.

.container-main{   display: grid;   grid-template-columns: repeat(6, 1fr);   grid-gap: 20px; }  .container-inner {   display: grid;   grid-template-columns: repeat(3, 1fr);   grid-gap: 10px; }  .container-nav {   display: grid;   grid-gap: 5px; }

Use grid-column and grid-row to determine the size of the individual grid items

Now it is time to put the layout into the shape we want it!

First is the grid-column property, which allows us to extend a grid item across n columns, where n is the number of columns to span. If you’re thinking this sounds an awful lot like the rowspan attribute that lets us extend cells across multiple rows in HTML tables, you wouldn’t be wrong.

It looks like this when we use it on a grid .item in our .container-main element, and on the .inner-item elements in .container-inner:

.item {   grid-column: span 6; }  .item-inner {   grid-column: span 3; }

What we’re saying here is that each item span six rows in our main container and three rows in our inner container — which is the total number of columns in each container.

An interesting thing about CSS Grid is that we are able to name the lines of the grid. They come with implicit names out of the box but naming them is a powerful way to distinguish between the starting and ending lines for each column on the track.

We can change the number of columns and rows the items should span at different breakpoints:

@media screen and (min-width: 600px) {   .item-type-b {     grid-column: span 3;   }    .item-inner {     grid-column: span 1;   } }  @media screen and (min-width: 900px) {   .item {     grid-column: span 2;     grid-row: span 2;   }    .item-type-b{     grid-row: span 1;   }    .item-inner{     grid-column: span 3;   } }

Using grid-auto-flow to control the placing of the elements

CSS Grid places elements one row after the other. This is why the result in our example looks like this at the moment:

A column-by-column placement can be achieved by setting the grid-auto-flow property to column (row is the default value). Our layout will profit from column-wise placement in two cases. First, it makes our menu items finally appear in a horizontal orientation. Secondly, it brings the elements of the container class into the desired grouping.

The final result

Conclusion: More or less specification?

The grid system allows us to work under the motto, “make as many specifications as necessary, but as few as possible.” We’ve only covered a few of the specifications necessary to turn elements into a CSS grid container and the items inside it into grid items for the sake of showing just how little you need to know to build even complex layouts with CSS Grid.

CSS Grid supports additional use cases where:

  • We want to make even fewer specifications in order to instead rely more on automatic positioning.
  • We want to make even more specifications in order to determine more details of the resulting layout.

If the first case applies, then it’s worth considering the following additional grid options:

  • When creating the grid with grid-template-columns, you can have the grid system automatically determine the width of individual columns with the auto keyword or adapt it to the existing content with the settings min-content, max-content, or fit-content.
  • You can let the grid system automatically determine the number of required columns with the help of repeat, auto-fill, auto-fit, and minmax. Even media queries can become redundant and these tools help make things flexible without adding more media queries.

Here are a couple of articles on the topic that I recommend: Becoming a CSS Grid Ninja! and Auto-Sizing Columns in CSS Grid: auto-fill vs. auto-fit.

If the second case applies, CSS Grid offers even more settings options for you:

  • You can explicitly specify the width of the columns in the unit of your choice (e.g. px or %) using the grid-template-columns property. In addition, the property grid-template-rows is available to define the number and width of rows, should there be a specific number of them. 
  • You can also define specific column or row numbers for positioning as values for grid-column and grid-row (or use the properties grid-column-start, grid-column-end, grid-row-start, or grid-row-end).

And we haven’t even gotten into CSS Grid alignment! Still, the fact that we can accomplish so much without even broaching that topic shows how powerful CSS Grid is.

The post 4 CSS Grid Properties (and One Value) for Most of Your Layout Needs appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]