본문 바로가기
  • 바쁜 일상 속 작은 기억
CSS

Animating Css Grid

by hellomingure 2023. 6. 7.

I'm pleased to shine a light on the fact that the CSS grid-template-rows
and grid-template-columns properties are now animatable in all major web browsers!

나는 CSS grid-template-rows와 grid-template-columns 속성들이 이제 주요 웹 브라우저에서 애니메이션 가능해진 사실을 밝힐 수 있어서 기쁘다.

 

Well, CSS Grid has technically supported animations for a long time, as it's baked right into the CSS Grid Layout Module Level 1 spec.

음, CSS grid layout module level 1 spec에 기본적으로 포함되어있기 때문에 CSS Grid는 오래 전부터 기술적으로 애니메이션이 지원됐었다.

 

But animating these grid properties only recently gained supported by all three major browsers. Shall we take a look at a few examples to get the creative juices flowing?

그러나 이 grid 속성에 애니메이션을 적용하는것은 최근에야 모든 주요 브라우저에서 사용되도록 지원되었다. 이 창의력을 발휘할 수 있는 몇가지 예를 들어보자.

Table of contents

  • Expanding sidebar
  • Expanding Panels
  • Adding Rows and Columns
  • A few more examples

Expanding sidebar

First of all, this is what we're talking about:

첫번째로, 이것이 우리가 말하고자 하는 것이다:

 

A simple two-column grid. Now, before, you might not have built this using CSS Grid because animations and transitions weren't supported, but what if you wanted the left column - perhaps a sidebar navigation - to expand on hover? Well, now that's possible.

하나의 간단한 두 열의 grid. 지금부터, 이전에는 animations 과 transitions 가 지원되지 않았기 때문에 CSS grid를 이용해서 만들 수 없었을 것이다. 그러나 만약 너가 왼쪽 열을 hover했을 때 확장하고싶다면? 글쎄, 이제는 가능하다.

 

I know what you're thinking: "Animating a CSS property? Easy peasy, I've been doing it for years!" Me too. However, I ran into an interesting snag while experimenting with a particular use case.

당신이 무슨 생각을 하는지 잘 안다: "애니메이션을 적용한 CSS 속성? 쉽지, 지금까지 해왔는걸!" 나도 그렇다. 그러나 특정 사용 케이스를 실험하는동안 흥미로운 걸림돌에 부딪쳤다.

 

So, we want to transition the grid itself (specifically grid-template-columns, which is set on the .grid class in the example). But the left column (.left) is the selector that requires the :hover pseudo-class. While JavaScript can solve this conundrum easily - thanks, but no thanks - we can accomplish it with CSS alone.

그래서, 우리는 grid 자체를 전환하려고 한다. (정확하게는 예제의 .grid클래스에 있는 grid-template-columns). 그러나, 이 왼쪽 열 (.left)은 :hover를 필요로 하는 선택자이다. JavaScript는 이 난제를 쉽게 해결 할 수 있지만, 우리는 CSS만 이용해서 해결할 수 있다.

Let's walk through the whole thing, starting with the HTML. Pretty standard stuff really... a grid with two columns.

HTML부터 시작해서 살표보겠습니다. 매우 전형적인것들... 두 개의 열이 있는 그리드입니다.

<div class='grid'>
    <div class='left'></div>
    <div class='right'></div>
</div>

Putting the cosmetic CSS aside, you'll first need to set display: grid on the parent container (.grid) 꾸미기용 CSS는 제쳐두고, 바로 첫번째로 부모 컨테이너에 display: grid 가 필요할것이다.

.grid {
    display: grid;
}

Next, we can define and size the two columns using the grid-template-columns property. We'll make the left column super narrow, and later increase its width on hover. The right column takes up the rest of the remaining space, thanks to the auto keyword.

그 다음, grid-template-columns를 이용하여 두 열을 정의하고 두 열의 사이즈를 정할 수 있다. 우리는 제일 왼쪽 열을 가장 좁게 만들고, hover됐을 때 그 가로길이만큼 증가하게 만들것이다. 그 오른쪽 열은 고맙게도 auto 키워드 덕분에 나머지 공간을 차지하게 됩니다.

.grid {
    display: grid;
    grid-template-columns: 48px auto;
}

We know we're going to animate this things, so let's go ahead and throw a transition in there while we're at it so the change between state is smooth and noticeable.

우리는 이것들이 애니메이션 될것이란 것을 안다. 그러니 어서 그 변화상태 중간에 스무스하고 알아차릴 수 있게 transition을 적용해보자

.grid {
    display: grid;
    grid-template-columns: 48px auto;
    transition: 300ms;
}

That's it for the .grid! All that's left is to apply the hover state. Specifically, we're going to override the grid-template-columns property so that the left column takes up a greater amount of space on hover.

.grid를 위한것이 끝났다! 이제 hover 상태를 적용하기 위한것만 남았다. 특히, grid-template-columns 속성을 덮어쓸 것인데, 이 왼쪽 행이 hover되었을 때 가장 큰 공간을 차지하게 될 것이다.

 

This alone isn't all that interesting, although it's awesome that animations and transitions are supported now in CSS Grid. What's more interesting is that we can use the relatively new :has() pseudo-class to style the parent container (.grid) while the child (.left) is hovered.

 

.grid:has(.left:hover){
    /* Hover styles */
}

In plain English this is saying, "Do something to the .grid container if it containes an element named .left insides of it that is in a hover state." That's why :has() is often referred to as a "parent" selector. We can finally select a parent based on the children it contains - no JavaScript required!

so, let's increase the width of the .left column to 30% when it is hovered. The .right column will continue to take up all the leftover space:

.grid {
    display: grid;
    transition: 300ms;
    grid-template-columns: 48px auto;
}

.grid:has(.left:hover) {
    grid-template-columns: 30% auto;
}

We could use CSS variables as well, which may or may not look cleaner depending on your personal preferences (or you might be using CSS variables in your project anyway):

.grid {
    display: grid;
    transition: 300ms;
    grid-template-columns: var(--left, 48px) auto;
}

.grid:has(.left:hover) {
    --left: 30%;
}

I love that CSS grids can be animated now, but the fact that we can build this particular example with just nine lines of CSS is even more astounding.

Expanding Panels

This example transitions the grid container (the column widths) but also the individual columns (their background colors). It's ideal for providing more content on hover.

It's worth remembering that the repeat() function sometimes produces buggy transitions. which is why I set the width of each column individually (i.e. grid-template-columns: 1fr 1fr 1fr).

Adding Rows and Columns

This example animatedly "adds" a column to the grid. However - you guessed it - this scenario has a pitfall too. The requirement is that the "new" column must not be hidden (i.e. set to display:none), and CSS Grid must acknowledge its existence while setting its width to 0fr.

So, for a three-column grid - grid-template-columns: 1fr 1fr 0fr (yes, the unit must be declared even though the value is 0!) transitions into grid-template-columns: 1fr 1fr 1fr correctly, but grid-template-columns: 1fr 1fr doesn't. In hindsight, this actually makes perfect sense considering what we know about how transitions work.

A few more examples

Because why not?

'CSS' 카테고리의 다른 글

[CSS] CSS 초기화  (0) 2023.03.11
[CSS] 1. 베이스 규칙  (0) 2023.03.10