현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

그리드는 기존의 설계 도구이며 다수의 웹 사이트 레이아웃은 그리드를 기반으로 하고 있습니다. 이 기사에서는 그리드 기반 디자인과 CSS를 사용하여 그리드를 생성하는 방법을 살펴 봅니다. 현재 브라우저에서 사용 가능한 새로운 기술을 이용합니다.

Prerequisites: HTML basics (study Introduction to HTML), and an idea of how CSS works (study Introduction to CSS and Styling boxes.)
Objective: To understand the fundamental concepts behind grid layout systems, and how to implement a grid layout on a web page.

그리드 레이아웃이란?

그리드는 단순히 디자인 요소를 일렬로 배열 할 수있는 패턴을 만드는 가로 및 세로 선 컬렉션입니다. 그들은 우리가 웹 사이트를보다 일관성있게 제공하면서 페이지간에 이동하면서 요소가 돌아 가지 않거나 폭이 변하지 않는 디자인을 만드는 데 도움이됩니다.

그리드는 일반적으로 ,, 그리고 각 행과 열 사이의 갭 - 일반적으로 거터 (gutters)라고합니다.

[Temporary diagram; will be replaced by a better diagram soon.]

Note: It may seem surprising to anyone coming from a design background that CSS doesn’t have an inbuilt grid system, and instead we seem to be using a variety of suboptimal methods to create grid-like designs. As you’ll discover in the last part of this article this is set to change, however you are likely to need to know the existing methods of creating grids for some time to come.

프로젝트에 '그리드 시스템' 사용하기

사이트 또는 애플리케이션 전반에서 일관된 경험을 보장하기 위해 처음부터 그리드 시스템을 기반으로한다는 것을 의미합니다. 특정 요소가 다른 요소와 얼마나 관련되어 있는지 생각할 필요가 없습니다. 선택 항목은 "이 요소가 펼칠 그리드의 열 수"로 제한됩니다.

귀하의 "그리드 시스템"은 단순히 설계 프로세스에서 일반 그리드를 사용하기로 한 결정 일 수 있습니다. Photoshop과 같은 그래픽 편집 응용 프로그램에서 디자인을 시작하면이 과정에서 참조 할 격자를 만들 수 있습니다.
(Elliot Jay Stocks의 A better Photoshop grid for responsive web design 참조)

그리드 시스템은 CSS를 통해 그리드를 시행하는 데 사용하는 타사 또는 프로젝트를 위해 만든 프레임 워크 일 수도 있습니다.

간단한 그리드 프레임 워크 만들기

프로젝트를위한 간단한 그리드 프레임 워크를 만드는 방법부터 살펴 보겠습니다.

현재 대부분의 격자 형 레이아웃은 수레를 사용하여 작성됩니다. float에 대한 이전 기사를 읽었다면이 기법을 사용하여 다중 열 레이아웃을 만드는 방법을 이미 보았습니다.이 방법은이 방법을 사용하는 모든 그리드 시스템의 핵심입니다.

격자 프레임 워크의 가장 쉬운 유형은 고정 너비입니다. 우리는 우리가 원하는 전체 너비, 원하는 열의 수 및 거터와 열의 넓이를 산출해야합니다. 대신 브라우저 너비에 따라 커지거나 축소되는 기둥을 사용하여 그리드에 디자인을 배치하기로 결정한 경우에는 기둥과 그루터 사이의 너비 비율을 계산해야합니다.

다음 섹션에서는 두 가지를 만드는 방법을 살펴 보겠습니다. 우리는 12 개의 열 그리드를 생성 할 것입니다 - 12가 6, 4, 3 및 2로 나누어 떨어지면 다른 상황에 매우 적응할 수있는 매우 일반적인 선택입니다.

A simple fixed width grid

 

고정 너비 열을 사용하는 그리드 시스템을 먼저 만들 수 있습니다.

다음 마크업을 포함하는 샘플파일(simple-grid.html)의 로컬 복사본을 만들어 시작하십시오.

 

<div class="wrapper">
  <div class="row">
    <div class="col">1</div>
    <div class="col">2</div>
    <div class="col">3</div>
    <div class="col">4</div>
    <div class="col">5</div>
    <div class="col">6</div>
    <div class="col">7</div>
    <div class="col">8</div>
    <div class="col">9</div>
    <div class="col">10</div>
    <div class="col">11</div>
    <div class="col">12</div>
  </div>
  <div class="row">
    <div class="col span1">13</div>
    <div class="col span6">14</div>
    <div class="col span3">15</div>
    <div class="col span2">16</div>    
  </div>
</div>

목표는이를 12 개의 열 그리드에서 두 행의 데모 격자로 바꾸는 것입니다. 개별 열의 크기를 보여주는 맨 위 행, 두 번째 행은 그리드의 다른 크기의 영역을 나타냅니다.

<style> 요소에서 래퍼 컨테이너에 980 픽셀의 너비와 20 픽셀의 오른쪽에 패딩이있는 다음 코드를 추가합니다. 이렇게하면 전체 열 / 거터 폭에 대해 960 픽셀을 남겨 둡니다.이 경우 box-sizing을 모든 요소의 테두리 상자로 설정했기 때문에 여백은 총 내용 너비에서 뺍니다 (자세한 설명을 위해 상자 모델을 완전히 변경하는 방법 참조).

* {
  box-sizing: border-box;
}
    

body {
  width: 980px;
  margin: 0 auto;
}

.wrapper {
  padding-right: 20px;
}

이제 그리드의 각 행을 감싸는 행 컨테이너를 사용하여 다른 행에서 한 행을 지웁니다. 이전 규칙 아래에 다음 규칙을 추가하십시오.

.row {
  clear: both;
}

이 규칙을 적용하면 전체 열 12개를 만드는 요소로 각 행을 완전히 채울 필요가 없습니다. 행은 분리된 채로 유지되며 서로 간섭하지 않습니다.

컬럼간 여백은 20 픽셀입니다. (첫 번째 열을 포함하여 각 열의 왼쪽에 여백을 만들어 컨테이너의 오른쪽에 20 픽셀의 여백을 균형있게 만듭니다. 그래서 총 12개의 여백이 있습니다.) 12 x 20 = 240입니다.

우리는 총 너비 960 픽셀에서 이 값을 뺄 필요가 있습니다. 이 값은 우리 컬럼에 720 픽셀을 줍니다. 이제이를 12로 나누면 각 열의 너비가 60 픽셀이어야합니다.

다음 단계는 클래스 .col 에 대한 규칙을 만들고 왼쪽으로 20 픽셀의 margin-left 여백을 형성하는 것입니다. width 60 픽셀.
CSS 하단에 다음 규칙을 추가하십시오.

.col {
  float: left;
  margin-left: 20px;
  width: 60px;
  background: rgb(255, 150, 150);
}

단일 열의 맨 위 행이 격자로 깔끔하게 배치됩니다.

Note: We've also given each column a light red color so you can see exactly how much space each one takes up.

둘 이상의 열을 스팬시키려는 레이아웃 컨테이너에는 width 값을 필요한 열 수 (그 사이에있는 여백)에 맞게 조정하는 특수 클래스가 있어야합니다. 컨테이너가 2 열에서 12 열까지 확장 될 수 있도록 추가 클래스를 만들어야합니다. 각 너비는 해당 열 수의 열 너비와 거터 너비를 더한 결과로 항상 열의 수보다 1이 작습니다.

CSS 하단에 다음을 추가하십시오:

/* Two column widths (120px) plus one gutter width (20px) */
.col.span2 { width: 140px; }
/* Three column widths (180px) plus two gutter widths (40px) */
.col.span3 { width: 220px; }
/* And so on... */
.col.span4 { width: 300px; }
.col.span5 { width: 380px; }
.col.span6 { width: 460px; }
.col.span7 { width: 540px; }
.col.span8 { width: 620px; }
.col.span9 { width: 700px; }
.col.span10 { width: 780px; }
.col.span11 { width: 860px; }
.col.span12 { width: 940px; }

이러한 클래스를 생성하여 이제 격자에 다양한 너비의 열을 배치 할 수 있습니다. 효과를 보려면 브라우저에서 페이지를 저장하고 로드하십시오.

Note: If you are having trouble getting the above example to work, try comparing it against our finished version on GitHub (see it running live also).

요소의 클래스를 수정하거나 일부 컨테이너를 추가 및 제거하여 레이아웃을 어떻게 변경할 수 있는지보십시오. 예를 들어 두 번째 행을 다음과 같이 만들 수 있습니다.:

<div class="row">
  <div class="col span8">13</div>
  <div class="col span4">14</div>
</div>

이제 그리드 시스템이 작동하고 각 행의 행과 열 수를 정의한 다음 각 컨테이너에 필요한 내용을 채웁니다.

Creating a fluid grid

그리드는 잘 작동하지만 고정 너비가 있습니다. 브라우저 viewport 에서 사용 가능한 공간으로 확장하고 축소 할 수있는 유연한 (유동적인) 그리드가 정말로 필요합니다. 이를 위해 참조 픽셀 너비를 사용하여 백분율로 변환 할 수 있습니다.

고정폭을 유연한 백분율 기반으로 변환하는 방정식은 다음과 같습니다.

target / context = result

우리의 열 너비에 대한 우리의 목표 너비는 60 픽셀이고 컨텍스트는 960 픽셀 래퍼입니다. 다음을 사용하여 비율을 계산할 수 있습니다.

60 / 960 = 0.0625

그런 다음 소수점 2 자리를 이동하여 비율 6.25 %를 얻습니다. 따라서 CSS에서 60 픽셀 열 너비를 6.25 %로 바꿀 수 있습니다.

우리는 여백의 너비와 똑같이해야합니다:

20 / 960 = 0.02083333333

So we need to replace the 20 pixel margin-left on our .col rule and the 20 pixel padding-right on .wrapper with 2.08333333%.

Updating our grid

To get started in this section, make a new copy of your previous example page, or make a local copy of our simple-grid-finished.html code to use as a starting point.

Update the second CSS rule (with the .wrapper selector) as follows:

body {
  width: 90%;
  max-width: 980px;
  margin: 0 auto;
}

.wrapper {
  padding-right: 2.08333333%;
}

Not only have we given it a percentage width, we have also added a max-width property in order to stop the layout becoming too wide.

Next, update the fourth CSS rule (with the .col selector) like so:

.col {
  float: left;
  margin-left: 2.08333333%;
  width: 6.25%;
  background: rgb(255, 150, 150);
}

Now comes the slightly more laborious part — we need to update all our .col.span rules to use percentages rather than pixel widths. This takes a bit of time with a calculator; to save you some effort, we've done it for you below.

Update the bottom block of CSS rules with the following:

/* Two column widths (12.5%) plus one gutter width (2.08333333%) */
.col.span2 { width: 14.58333333%; }
/* Three column widths (18.75%) plus two gutter widths (4.1666666) */
.col.span3 { width: 22.91666666%; }
/* And so on... */
.col.span4 { width: 31.24999999%; }
.col.span5 { width: 39.58333332%; }
.col.span6 { width: 47.91666665%; }
.col.span7 { width: 56.24999998%; }
.col.span8 { width: 64.58333331%; }
.col.span9 { width: 72.91666664%; }
.col.span10 { width: 81.24999997%; }
.col.span11 { width: 89.5833333%; }
.col.span12 { width: 97.91666663%; }

Now save your code, load it in a browser, and try changing the viewport width — you should see the column widths adjust nicely to suit. Great!

Note: If you are having trouble getting the above example to work, try comparing it against our finished version on GitHub (see it running live also).

Easier calculations using the calc() function

You could use the calc() function to do the math right inside your CSS — this allows you to insert simple mathematical equations into your CSS values, to calculate what a value should be. It is especially useful when there is complex math to be done, and you can even compute a calculation that uses different units, for example "I want this element's height to always be 100% of its parent's height, minus 50px". See this example from a MediaRecorder API tutorial.

Anyway, back to our grids! Any column that spans more than one column of our grid has a total width of 6.25% multiplied by the number of columns spanned plus 2.08333333% multiplied by the number of gutters (which will always be the number of columns minus 1). The calc() function allows us to do this calculation right inside the width value, so for any item spanning 4 columns we can do this, for example:

.col.span4 {
  width: calc((6.25%*4) + (2.08333333%*3));
}

Try replacing your bottom block of rules with the following, then reload it in the browser to see if you get the same result:

.col.span2 { width: calc((6.25%*2) + 2.08333333%); }
.col.span3 { width: calc((6.25%*3) + (2.08333333%*2)); }
.col.span4 { width: calc((6.25%*4) + (2.08333333%*3)); }
.col.span5 { width: calc((6.25%*5) + (2.08333333%*4)); }
.col.span6 { width: calc((6.25%*6) + (2.08333333%*5)); }
.col.span7 { width: calc((6.25%*7) + (2.08333333%*6)); }
.col.span8 { width: calc((6.25%*8) + (2.08333333%*7)); }
.col.span9 { width: calc((6.25%*9) + (2.08333333%*8)); }
.col.span10 { width: calc((6.25%*10) + (2.08333333%*9)); }
.col.span11 { width: calc((6.25%*11) + (2.08333333%*10)); }
.col.span12 { width: calc((6.25%*12) + (2.08333333%*11)); }

Note: You can see our finished version in fluid-grid-calc.html (also see it live).

Note: If you can't get this to work, it might be because your browser does not support the calc() function, although it is fairly well supported across browsers — as far back as IE9.

Semantic versus “unsemantic” grid systems

Adding classes to your markup to define layout means that your content and markup becomes tied to its visual presentation. You will sometimes hear this use of CSS classes described as being “unsemantic” — describing how the content looks — rather than a semantic use of classes that describes the content. This is the case with our span2, span3, etc., classes.

These are not the only approach. You could instead decide on your grid and then add the sizing information to the rules for existing semantic classes. For example, if you had a <div> with a class of content on it that you wanted to span 8 columns, you could copy across the width from the span8 class, giving you a rule like so:

.content {
  width: calc((6.25%*8) + (2.08333333%*7));
}

Note: If you were to use a preprocessor such as Sass, you could create a simple mixin to insert that value for you.

Enabling offset containers in our grid

The grid we have created works well as long as we want to start all of the containers flush with the left hand side of the grid. If we wanted to leave an empty column space  before the first container — or between containers — we would need to create an offset class to add a left margin to our site to push it across the grid visually. More math!

Let's try this out.

Start with your previous code, or use our fluid-grid.html file as a starting point.

Let's create a class in our CSS that will offset a container element by one column width. Add the following to the bottom of your CSS:

.offset-by-one {
  margin-left: calc(6.25% + (2.08333333%*2));
}

Or if you prefer to calculate the percentages yourself, use this one:

.offset-by-one {
  margin-left: 10.41666666%;
}

You can now add this class to any container you want to leave a one column wide empty space on the left hand side of it. For example, if you have this in your HTML:

<div class="col span6">14</div>

Try replacing it with

<div class="col span5 offset-by-one">14</div>

Note: Notice that you need to reduce the number of columns spanned, to make room for the offset!

Try loading and refreshing to see the difference, or check out our fluid-grid-offset.html example (see it running live also). The finished example should look like this:

Note: As an extra exercise, can you implement an offset-by-two class?

Floated grid limitations

When using a system like this you do need to take care that your total widths add up correctly, and that you don’t include elements in a row that span more columns than the row can contain. Due to the way floats work, if the number of grid columns becomes too wide for the grid, the elements on the end will drop down to the next line, breaking the grid.

Also bear in mind that if the content of the elements gets wider than the rows they occupy, it will overflow and look like a mess.

The biggest limitation of this system is that it is essentially one dimensional. We are dealing with columns, and spanning elements across columns, but not rows. It is very difficult with these older layout methods to control the height of elements without explicitly setting a height, and this is a very inflexible approach too — it only works if you can guarantee that your content will be a certain height.

플렉스박스(Flexbox) 그리드란?

If you read our previous article about flexbox, you might think that flexbox is the ideal solution for creating a grid system. There are currently any number of flexbox-based grid systems available and flexbox can solve many of the issues that we’ve already discovered when creating our grid above.

However, flexbox was never designed as a grid system and poses a new set of challenges when used as one. As a simple example of this, we can take the same example markup we used above and use the following CSS to style the wrapper, row, and col classes:

body {
  width: 90%;
  max-width: 980px;
  margin: 0 auto;
}

.wrapper {
  padding-right: 2.08333333%;
}


.row {
  display: flex;
}

.col {
  margin-left: 2.08333333%;
  margin-bottom: 1em;
  width: 6.25%;
  flex: 1 1 auto;
  background: rgb(255,150,150);
}

You can try making these replacements in your own example, or look at our flexbox-grid.html example code (see it running live also).

Here we are turning each row into a flex container. With a flexbox-based grid we still need rows in order to allow us to have elements that add up to less than 100%. We set that container to display: flex.

On .col we set the flex property's first value (flex-grow) to 1 so our items can grow, the second value (flex-shrink) to 1 so the items can shrink, and the third value (flex-basis) to auto. As our element has a width set, auto will use that width as the flex-basis value.

On the top line we get twelve neat boxes on the grid and they grow and shrink equally as we change the viewport width. On the next line, however, we only have four items and these also grow and shrink from that 60px basis. With only four of them they can grow a lot more than the items in the row above, the result being that they all occupy the same width on the second row.

To fix this we still need to include our span classes to provide a width that will replace the value used by flex-basis for that element.

They also don’t respect the grid used by the items above because they don’t know anything about it.

Flexbox is one-dimensional by design. It deals with a single dimension, that of a row or a column. We can’t create a strict grid for columns and rows, meaning that if we are to use flexbox for our grid, we still need to calculate percentages as for the floated layout.

In your project you might still choose to use a flexbox ‘grid’ due to the additional alignment and space distribution capabilities flexbox provides over floats. You should, however, be aware that you are still using a tool for something other than what it was designed for. So you may feel like it is making you jump through additional hoops to get the end result you want.

써드파티(Third party) 그리드 시스템

Now that we understand the math behind our grid calculations, we are in a good place to look at some of the third party grid systems in common use. If you search for "CSS Grid framework" on the Web, you will find a huge list of options to choose from. Popular frameworks such as Bootstrap and Foundation include a grid system. There are also standalone grid systems, either developed using CSS or using preprocessors.

Let's take a look at one of these standalone systems as it demonstrates common techniques for working with a grid framework. The grid we will be using is part of Skeleton, a simple CSS framework.

To get started visit the Skeleton website, and choose "Download" to download the ZIP file. Unzip this and copy the skeleton.css and normalize.css files into a new directory.

Make a copy of our html-skeleton.html file and save it in the same directory as the skeleton and normalize CSS.

Include the skeleton and normalize CSS in the HTML page, by adding the following to its head:

<link href="normalize.css" rel="stylesheet">
<link href="skeleton.css" rel="stylesheet">

Skeleton includes more than a grid system — it also contains CSS for typography and other page elements that you can use as a starting point. We’ll leave these at the defaults for now, however — it’s the grid we are really interested in here.

Note: Normalize is a really useful little CSS library written by Nicolas Gallagher, which automatically does some useful basic layout fixes and makes default element styling more consistent across browsers.

We will use similar HTML to our earlier example. Add the following into your HTML body:

<div class="container">
  <div class="row">
    <div class="col">1</div>
    <div class="col">2</div>
    <div class="col">3</div>
    <div class="col">4</div>
    <div class="col">5</div>
    <div class="col">6</div>
    <div class="col">7</div>
    <div class="col">8</div>
    <div class="col">9</div>
    <div class="col">10</div>
    <div class="col">11</div>
    <div class="col">12</div>
  </div>
  <div class="row">
    <div class="col">13</div>
    <div class="col">14</div>
    <div class="col">15</div>
    <div class="col">16</div>   
  </div>
</div>


To start using Skeleton we need to give the wrapper <div> a class of container — this is already included in our HTML. This centers the content with a maximum width of 960 pixels. You can see how the boxes now never become wider than 960 pixels.

You can take a look in the skeleton.css file to see the CSS that is used when we apply this class. The <div> is centered using auto left and right margins, and a padding of 20 pixels is applied left and right. Skeleton also sets the box-sizing property to border-box like we did earlier, so the padding and borders of this element will be included in the total width.

.container {
  position: relative;
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

Elements can only be part of the grid if they are inside a row, so as with our earlier example we need an additional <div> or other element with a class of row nested between the content <div> and our actual content container <div>s. We've done this already as well.

Now let's lay out the container boxes. Skeleton is based on a 12 column grid. The top line boxes all need classes of one column to make them span one column.

Add these now, as shown in the following snippet:

<div class="container">
  <div class="row">
    <div class="one column">1</div>
    <div class="one column">2</div>        
    <div class="one column">3</div>
    /* and so on */
  </div>
</div>

Next, give the containers on the second row classes explaining the number of columns they should span, like so:

<div class="row">
  <div class="one column">13</div>
  <div class="six columns">14</div>
  <div class="three columns">15</div>
  <div class="two columns">16</div>   
</div>

Try saving your HTML file and loading it in your browser to see the effect.

Note: If you are having trouble getting this example to work, try comparing it to our html-skeleton-finished.html file (see it running live also).

If you look in the skeleton.css file you can see how this works. For example, Skeleton has the following defined to style elements with “three columns” classes added to them.

.three.columns { width: 22%; }

All Skeleton (or any other grid framework) is doing is setting up predefined classes that you can use by adding them to your markup. It’s exactly the same as if you did the work of calculating these percentages yourself.

As you can see, we need to write very little CSS when using Skeleton. It deals with all of the floating for us when we add classes to our markup. It is this ability to hand responsibility for layout over to something else that makes using a framework for a grid system a compelling choice!

Skeleton is a simpler grid system than some of the frameworks you may come across. The grids in large frameworks such as Bootstrap and Foundation offer more functionality and additional breakpoints for various screen widths. However, they all work in a similar way — by adding specific classes to your markup you can control how the element is laid out using the predefined grid.

Native CSS Grids with Grid Layout

We said at the beginning of this article that CSS has not previously had a real system for creating grid layouts, but this is going to change. While we can’t use a native CSS grid system yet, in the coming year we should see browser support appear for the CSS Grid Layout Module.

Currently you can only use the technique we’ll be showing you in browsers that are implementing CSS Grid Layout “behind a flag” — meaning it is currently implemented, but in an experimental state that you need to switch on to use.

In Firefox, for example, you need to navigate to a URL of about:config, search for the layout.css.grid.enabled preference, and double click it to enable CSS Grids. You can find out how to use it in other browsers by visiting Grid by Example.

We looked at the Skeleton Grid framework above — like other third party grids and even hand-built grids, it requires that you add <div>s to form rows and then specify the number of columns the items in these rows will span.  

With CSS Grid Layout you can specify your grid entirely in CSS, without needing to add these helper classes to the markup at all. Let’s take our simple example and see how we would create that same layout using CSS Grid Layout.

Building a native grid

First, get started by making a local copy of the css-grid.html file. It contains the following markup:

<div class="wrapper">
  <div class="col">1</div>
  <div class="col">2</div>
  <div class="col">3</div>
  <div class="col">4</div>
  <div class="col">5</div>
  <div class="col">6</div>
  <div class="col">7</div>
  <div class="col">8</div>
  <div class="col">9</div>
  <div class="col">10</div>
  <div class="col">11</div>
  <div class="col">12</div>
  <div class="col">13</div>
  <div class="col span6">14</div>
  <div class="col span3">15</div>
  <div class="col span2">16</div>       
</div>

This time we have a parent <div> with a class of wrapper, and then all of the child elements just appear directly inside the wrapper — no row elements. We have added a class to the items that should span more than one column.

Now add the following into the <style> element:

.wrapper {
  width: 90%;
  max-width: 960px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-gap: 20px;
}

.col {
  background: rgb(255,150,150);
}

Here we set the .wrapper rule so it is 90% of the body width, centered, and has a max-width of 960px.

Now for the CSS grid properties. We can declare a grid using the grid value of the display property, set up a gutter with the grid-gap property and then create a grid of 12 columns of equal width using grid-template-columns, the new repeat() function, and a new unit defined for grid layout — the fr unit.

The fr unit is a fraction unit — it describes a fraction of the available space in the grid container. If all columns are 1fr, they will each take up an equal amount of space. This removes the need to figure out percentages to create a flexible grid.

Having created a grid, the grid auto-placement rules will immediately lay out our boxes on this grid and we get a twelve column flexible grid layout.

To style the containers that span multiple column tracks on the grid we can use the grid-column property. To span 6 columns for example:

.span6 {
  grid-column: auto / span 6;
}

To span 3:

.span3 {
  grid-column: auto / span 3;
}

The value before the forward slash is the start line — in this case we are not explicitly setting that and allowing the browser to place the item on the next available line. We can then set it to span 6, 3 or however many lines we want.

Add the following at the bottom of your CSS:

.span2 { grid-column: auto / span 2;}
.span3 { grid-column: auto / span 3;}
.span4 { grid-column: auto / span 4;}
.span5 { grid-column: auto / span 5;}
.span6 { grid-column: auto / span 6;}
.span7 { grid-column: auto / span 7;}
.span8 { grid-column: auto / span 8;}
.span9 { grid-column: auto / span 9;}
.span10 { grid-column: auto / span 10;}
.span11 { grid-column: auto / span 11;}
.span12 { grid-column: auto / span 12;}

Try saving and refreshing, and you'll see that the containers span multiple columns as appropriate. Cool!

CSS grids are two-dimensional, so as the layout grows and shrinks the elements remain lined up horizontally and vertically.

You can test this by replacing your last 4 col <div>s with the following:

<div class="col">13some<br>content</div>
<div class="col span6">14this<br>is<br>more<br>content</div>
<div class="col span3">15this<br>is<br>less</div>
<div class="col span2">16</div>

Here we've deliberately added in some line break (<br>) tags to force some of the columns to become taller than others. If you try saving and refreshing, you'll see that the columns adjust their height to be as tall as the tallest container, so everything stays neat and tidy.

The final layout looks like so:

Note: If you are having trouble getting this example to work, you can check your code against our finished version (also see it running live).

Other nice CSS grid features

With CSS grids, we don’t need to push things along by way of margins to offset them. Try making these changes in your CSS:

.content {
  grid-column: 2 / 8;
}
<div class="col span2 content">16</div>

Container 16 will now span columns 2 to 8, on the next available row where it can fit.

We can span rows just as easily as columns:

.content {
  grid-column: 2 / 8;
  grid-row: 3 / 5;
}

Container 16 will now span rows 3 to 5, as well as columns 2 to 8.

We also don’t need to use a margin to fake gutters or calculate their widths explicitly — CSS grid has this functionality built right in with the grid-gap property.

We’re just touching the surface of what is possible with CSS Grid Layout, but the key thing to understand in the context of this article is that you don’t need to create a grid system with grid — it is one. You can write CSS that places an item directly onto a predefined grid. This is the first time it has been possible with CSS, and this will get a lot more use once browser support solidifies.

Active learning: Write your own simple grid

In the Introduction to CSS layout aticle, we included a section about CSS tables, which included a simple form example (see the css-tables-example.html live example, and the source code). We'd like you to take a copy of this example, and do the following:

  1. Remove the <div> elements inside the <form> — you no longer need these, as CSS Grids can handle placing the content on rows and columns for you.
  2. Use the CSS grid properties to create a layout for your form as close to the original as you can get. You will have to set a width on the containing element, and think about how to set column gaps as well as row gaps.

Note: Have a go at doing this first, and if you get really stuck, you can check your code against our css-tables-as-grid.html example. Don't cheat — try the exercise first!

개요

Having read this article you should now have an understanding of how grid layouts and grid frameworks work in CSS. You have also had a peek into the future of CSS grids and should now understand that the grid frameworks we use today are essentially a stopgap solution until we have a widely supported native way of achieving this in CSS.

 

In this module

 

문서 태그 및 공헌자

이 페이지의 공헌자: sonsoonmee
최종 변경: sonsoonmee,