본문 바로가기

개발/CSS3

CSS 그리드 예제 배우기 (새로운 CSS 그리드 튜토리얼)

레이아웃 미리보기

이것은 우리가 구축 할 아주 간단한 레이아웃입니다. 나는 우리가 상대적으로 쉽게 이것을 통해 바람을 피울 수 있도록 간단하게 유지했습니다. 그것은 내 허구의 자유 론자의 견해 중 일부를지지하기위한 가상의 레이아웃입니다!

프로젝트 설정

이 튜토리얼을 가능한 한 정확하게 숙독하기 위해 프레임 워크 또는 빌드 도구를 포함하지 않을 것입니다. 말 그대로 단일 HTML, CSS 및 이미지 파일로 작업 할 것입니다.

새 프로젝트 폴더를 만들고  다음 내용  이있는 index.html 파일 과 함께 빈 index.css 파일을 추가하십시오 .

<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>

        <title>CSS Grid Tutorial</title>
        <meta http-equiv="x-ua-compatible" content="ie=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700" rel="stylesheet">
        <link media="all" type="text/css" rel="stylesheet" href="index.css">

    </head>
    <body>

    </body>
</html>

또한 단일 로고 그래픽을 다운로드하십시오 (마우스 오른쪽 단추로 클릭하고 다른 이름으로 저장 한 다음 다른 2 개의 파일 옆에있는 프로젝트 폴더에 추가하십시오).

HTML 정의하기

 위에서 <body> 태그 안에 3 개의 섹션을 정의 할 것입니다. 머리말, 주요 내용 단면도 및 3 개의위원회의 순서가없는 목록을 포함 할 꼬리말 :

        <header>
            <a href="#">Libertians > *</a>
        </header>

        <div class="container">
            <div id="content">
                <h1>Down with the state</h1>
                <p>Abandon the left vs. right paradigm and adopt new ideals, where consistency and logic reign supreme.</p>
            </div>
            <img src="logo.png" />
        </div>

        <footer>
            <ul>
                <li>
                    <span>But what about the roads?</span>
                    You just don't understand economics, like supply and demand. Don't worry kiddo, where there's a demand there will be a supply; we'll all have our roads.
                </li>
                <li>
                    <span>Is taxation theft?</span>
                    If I came to your house with some heavily armed buddies, demanded that you and your neighbors give me a percentage of your income, in return for some crappy monopolized services that you didn't ask for, would you consider that theft?
                </li>
                <li>
                    <span>So, what you're saying is...?</span>
                    Libertarians want to live in a world where gay couples can protect their poppy fields with fully automatic weapons.

A world where voluntaryism and property rights are treated with the highest respect.
                </li>

                <li> <!-- Repeat this 3 more times, so we have a total of 6 -->
                <li> <!-- Repeat this 3 more times, so we have a total of 6 -->
                <li> <!-- Repeat this 3 more times, so we have a total of 6 -->
            </ul>
        </footer>

자, 이제 간단히 CSS 그리드를 사용하여이 나쁜 소년을 구성 해 봅시다.

기본 CSS 규칙 세트 정의

기본적인 미학을 위해서 CSS 규칙과 속성을 정의 해보자. 여기에는 글꼴, 색상 등과 같은 기본적인 내용이 포함됩니다.

에서 index.css  다음 속성을 붙여 넣습니다 :

body {
    font-family: 'Source Sans Pro';
    background:red;
    margin:0;
    color:white;
}

a {
    text-decoration:none;
    color:red;
    font-size:1.8em;
    font-weight:700;
}
img { 
    width:150px;
}
header {
    background:#FFFFFF;
    padding: 1em;
}

.container {
    padding: 4em 1em;
}

footer {
    background:#571212;
}

ul {
    margin:0;padding:0;
}
ul li {
    padding: 2em;
    color:#E98A8A;
}
ul li span {
    display:block;
    font-size:1.4em;
    margin-bottom:1em;
    color: white;
}

이것은 레이아웃을 위해 필요한 유일한 정규 CSS입니다. 이제 남아있는 유일한 것은 CSS 그리드 속성을 정의하는 것입니다.

CSS 그리드 정의하기

기본 CSS 그리드를 정의하기  위해 요소에 display : grid 를 배치 합니다 . 이것을하는 것이 어디에서 의미가 있습니까? 음, 우리의 주요 내용 영역에는 2 개의 열이 있고 바닥 글 영역에는 3 개의 열이 있습니다.

상단 그리드에는 1 행과 2 열이 있습니다. 하단 그리드 (6 개의 다른 <li>  요소가있는 경우)에는 2 행 3 열이 있습니다.

CSS 격자를 상위 컨텐츠 영역에 추가해 보겠습니다.

.container {
    display:grid;
    grid-template-columns: 66% auto;
    padding: 4em 1em;
}

격자 템플릿 열  속성은 공백으로 분리 된 값을 정의함으로써 행해진 다 열 수를 정의한다. 각 값과 공백은 다른 열을 나타냅니다.

바닥 글 그리드 요소를 정의합시다 :

ul {
    display:grid;
    list-style-type:none;
    margin:0;padding:0;
    grid-template-columns: repeat(3, auto);
    grid-template-rows: repeat(2, auto);
}

이번에는 repeat () 를 사용했는데 이는 빠른 방법입니다 : grid-template-columns : auto auto auto 

또한  열과 동일한 방식으로 작동하는 그리드 템플릿 행 을 추가 했습니다. 단, 단순히 행을 정의하는 것만 다릅니다.

이 값들을 시험해보십시오! 2 열과 3 행을 원한다면 위의 규칙 집합에서 3과 2를 간단히 반대로 입력하면됩니다.

또한 그래픽을 중앙에 배치하려면 어떻게해야합니까? CSS 그리드를 사용하면 어린이 또는 항목을 아주 쉽게 정렬 할 수 있습니다. 당신은  항목을 배치하기 위해 justify-self 를 사용할 수 있습니다 :

img { 
    width:150px;
    justify-self:center;
}

CSS 그리드 및 템플릿 영역 중첩

물론 CSS 그리드를 중첩 할 수 있습니다. 실제 body 요소를 실제 그리드로 만들어 보겠습니다!

body {
    font-family: 'Source Sans Pro';
    background:red;
    margin:0;
    color:white;
    display:grid;
    grid-template-columns: auto;
    grid-template-rows: auto 60% 40%;
    grid-template-areas: 
    "header"
    "body"
    "footer";
}

좋아, 그럼 여기서 뭐하는거야? 우리는 1 열을 auto로 설정했으며 3 개의 다른 행 (머리글, 내용 및 바닥 글 섹션)이 있습니다.

grid-template-areas를  사용하면 이름을 참조하여 다양한 그리드 영역을 배치하고이 속성의 값에 배치 할 수 있습니다.

그러나 그것이 작동하려면, 각 룰 세트에서 이들 이름 (헤더, 본문, 바닥 글)을 정의해야합니다. 다음 속성 및 값을 추가하십시오.

header {
    grid-area: header;
    /* Other properties removed for brevity */
}

.container {
    grid-area: body;
    /* Other properties removed for brevity */
}

footer {
    grid-area: footer;
    /* Other properties removed for brevity */
}

이제 저장하고 새로 고침하면 아무 것도 변경되지 않은 것으로 보입니다. 그러나 반응 형 미디어 쿼리에서 작업 할 때 템플릿 영역의 진정한 힘이 작용합니다.

반응성 CSS 그리드

이상한 이유로 일부 작은 뷰포트에서 본문 섹션으로 바닥 글 섹션을 전환하고 싶다면 어떻게해야합니까?

단순한!

@media only screen and (max-width: 500px) {
    
    body {
        grid-template-areas: 
            "header"
            "footer"
            "body";
    }

}

이제 브라우저 창을 드래그하면이 두 격자 영역이 서로 자동으로 바뀝니다. 이전에는 순수한 CSS로는 불가능했지만 지금은 그렇습니다. 

바닥 글과 컨테이너 섹션을 모두 1 열로 만들고 (컨테이너 텍스트를 가운데에 맞 춥니 다)

@media only screen and (max-width: 500px) {
    
    body {
        grid-template-areas: 
            "header"
            "footer"
            "body";
    }

    ul, .container {
        grid-template-columns: auto;
        grid-template-rows: auto;
    }

    .container {
        text-align:center;
    }
    
}

이제는 반응이 좋은 CSS 그리드 레이아웃이 꽤 멋지게 보입니다!