CSS 고정 위치 지정 레이아웃 구현하기

CSSBeginner
지금 연습하기

소개

이 랩에서는 CSS 를 사용하여 고정 위치 레이아웃을 만드는 방법을 배우게 됩니다. 이는 웹 페이지에서 요소의 위치를 유지하기 위한 강력한 기술입니다. 이 랩은 고정 위치 지정의 개념을 이해하고, HTML 프로젝트 구조를 설정하며, 페이지 스크롤 중에도 요소가 고정된 상태로 유지되는 방식을 탐구하면서 사이드 광고에 고정 위치 지정을 적용하는 과정을 안내합니다.

단계별 지침을 따르면 position: fixed와 같은 CSS 위치 지정 속성을 사용하는 실질적인 기술을 습득하고, top, bottom, left, right 속성을 사용하여 요소의 위치를 정확하게 제어하는 방법을 배우게 됩니다. 이 랩은 페이지 스크롤에 관계없이 위치를 유지하는 반응형 (responsive) 이며 시각적으로 일관된 레이아웃을 만드는 실습 경험을 제공합니다.

고정 위치 지정 개념 이해하기

이 단계에서는 스크롤 여부에 관계없이 요소가 화면에서 고정된 위치에 유지되도록 하는 강력한 레이아웃 기술인 CSS 의 고정 위치 지정에 대해 배우게 됩니다.

고정 위치 지정은 페이지를 스크롤해도 요소가 화면의 정확히 동일한 위치에 유지되도록 하는 CSS 위치 지정 방법입니다. 다른 위치 지정 방법과 달리 고정 요소는 사용자가 페이지를 스크롤할 때 이동하지 않습니다.

간단한 예제를 통해 기본 개념을 살펴보겠습니다.

<!doctype html>
<html>
  <head>
    <style>
      .fixed-element {
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: #f1f1f1;
        padding: 10px;
        border: 1px solid #ddd;
      }
    </style>
  </head>
  <body>
    <div class="fixed-element">I'm a fixed element that stays in place!</div>
    <div style="height: 2000px;">
      Scroll down to see the fixed element remain in position
    </div>
  </body>
</html>

고정 위치 지정의 주요 특징:

  • CSS 에서 position: fixed; 사용
  • 브라우저 창을 기준으로 위치 지정
  • 페이지를 스크롤해도 이동하지 않음
  • top, bottom, left, 및 right 속성을 사용하여 정확하게 배치 가능

브라우저에서 볼 때의 예시 출력:

  • .fixed-element는 항상 화면 상단 및 오른쪽에서 20 픽셀 떨어진 위치에 유지됩니다.
  • 아래로 스크롤해도 이 요소는 정확히 동일한 화면 위치에 유지됩니다.

HTML 프로젝트 구조 설정

이 단계에서는 고정 위치 지정 레이아웃 데모를 위한 프로젝트 구조를 생성합니다. CSS 위치 지정 연습의 기반이 될 ~/project 디렉토리에 간단한 HTML 프로젝트를 설정합니다.

먼저, 프로젝트 디렉토리로 이동하여 필요한 파일을 생성합니다.

cd ~/project
mkdir fixed-positioning-demo
cd fixed-positioning-demo

이제 기본 HTML 파일 구조를 생성합니다.

touch index.html
touch styles.css

index.html 파일을 열고 다음 기본 HTML 구조를 추가합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Fixed Positioning Layout Demo</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="content">
      <h1>Fixed Positioning Layout</h1>
      <p>This is a sample page to demonstrate fixed positioning in CSS.</p>

      <!-- We'll add more content in subsequent steps -->
    </div>
  </body>
</html>

기본 CSS 파일 styles.css를 생성하고 초기 스타일을 추가합니다.

body {
  font-family: Arial, sans-serif;
  line-height: 1.6;
  margin: 0;
  padding: 0;
}

.content {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

예시 출력 구조:

~/project/fixed-positioning-demo/
├── index.html
└── styles.css

이 설정은 고정 위치 지정 기술을 시연하기 위해 다음 단계에서 구축할 깨끗하고 간단한 프로젝트 구조를 제공합니다.

사이드 광고에 고정 위치 지정 적용

이 단계에서는 CSS 를 사용하여 고정 위치 측면 광고를 만드는 방법을 배웁니다. 스크롤하는 동안 제자리에 유지되는 측면 광고 요소를 추가하기 위해 index.html 및 styles.css 파일을 수정합니다.

index.html 파일을 업데이트하여 측면 광고 요소를 포함합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Fixed Positioning Layout Demo</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="left-ad">
      <h3>Left Side Ad</h3>
      <p>This ad stays in place!</p>
    </div>

    <div class="right-ad">
      <h3>Right Side Ad</h3>
      <p>Another fixed advertisement</p>
    </div>

    <div class="content">
      <h1>Fixed Positioning Layout</h1>
      <p>Scroll down to see how the side advertisements remain fixed.</p>

      <!-- Add more content to create scrolling effect -->
      <div style="height: 2000px;">Long content to demonstrate scrolling</div>
    </div>
  </body>
</html>

styles.css 파일을 수정하여 광고에 고정 위치 지정을 적용합니다.

body {
  font-family: Arial, sans-serif;
  line-height: 1.6;
  margin: 0;
  padding: 0;
}

.content {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.left-ad,
.right-ad {
  position: fixed;
  width: 150px;
  background-color: #f4f4f4;
  padding: 10px;
  border: 1px solid #ddd;
}

.left-ad {
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.right-ad {
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

고정 위치 지정에 대한 주요 사항:

  • position: fixed;는 광고를 일정한 위치에 유지합니다.
  • left 및 right 속성은 화면 측면에 광고를 배치합니다.
  • top: 50% 및 transform: translateY(-50%)는 광고를 수직으로 중앙에 배치합니다.

브라우저에서의 예시 출력:

  • 두 개의 측면 광고가 화면에 고정되어 나타납니다.
  • 페이지를 스크롤할 때 광고는 제자리에 유지됩니다.
  • 광고는 화면에서 수직으로 중앙에 배치됩니다.

top 및 right 속성을 사용하여 요소 배치 조정

이 단계에서는 top, right, bottom, 및 left 속성을 사용하여 고정 위치 지정 요소의 배치를 정밀하게 제어하는 방법을 배웁니다. 이러한 CSS 속성을 사용하면 고정 요소를 화면에서 원하는 정확한 위치에 배치할 수 있습니다.

다양한 위치 지정 기술을 시연하기 위해 styles.css 파일을 업데이트합니다.

/* Previous styles remain the same */

.left-ad {
  position: fixed;
  top: 20px; /* 20 pixels from the top of the screen */
  left: 20px; /* 20 pixels from the left of the screen */
  width: 150px;
  background-color: #f4f4f4;
  padding: 10px;
  border: 1px solid #ddd;
}

.right-ad {
  position: fixed;
  top: 50%; /* Vertically centered */
  right: 20px; /* 20 pixels from the right of the screen */
  width: 150px;
  transform: translateY(-50%); /* Adjust for perfect centering */
  background-color: #e4e4e4;
  padding: 10px;
  border: 1px solid #ccc;
}

.bottom-ad {
  position: fixed;
  bottom: 20px; /* 20 pixels from the bottom of the screen */
  left: 50%; /* Horizontally centered */
  width: 300px;
  transform: translateX(-50%); /* Adjust for perfect centering */
  background-color: #d4d4d4;
  padding: 10px;
  text-align: center;
  border: 1px solid #bbb;
}

새로운 하단 광고를 포함하도록 index.html을 업데이트합니다.

<body>
  <div class="left-ad">
    <h3>Left Side Ad</h3>
    <p>Positioned 20px from top-left</p>
  </div>

  <div class="right-ad">
    <h3>Right Side Ad</h3>
    <p>Vertically centered</p>
  </div>

  <div class="bottom-ad">
    <h3>Bottom Ad</h3>
    <p>Centered at the bottom of the screen</p>
  </div>

  <div class="content">
    <h1>Fixed Positioning Layout</h1>
    <p>Explore different positioning techniques</p>

    <div style="height: 2000px;">Scroll to see fixed elements</div>
  </div>
</body>

주요 위치 지정 속성 설명:

  • top: 화면 상단으로부터의 거리
  • right: 화면 오른쪽으로부터의 거리
  • bottom: 화면 하단으로부터의 거리
  • left: 화면 왼쪽으로부터의 거리
  • transform: 완벽한 중앙 정렬을 위한 미세 조정

브라우저에서의 예시 출력:

  • 왼쪽 광고: 왼쪽 상단 모서리에서 20 픽셀
  • 오른쪽 광고: 오른쪽 측면에 수직으로 중앙 정렬
  • 하단 광고: 화면 하단에 중앙 정렬
  • 모든 요소는 스크롤하는 동안 고정 상태를 유지합니다.

고정 요소의 스크롤 동작 테스트

이 단계에서는 페이지가 스크롤되는 동안 이러한 요소가 어떻게 고정된 상태로 유지되는지 보여주기 위해 더 많은 콘텐츠를 추가하여 고정 위치 지정 요소의 고유한 스크롤 동작을 탐색합니다.

index.html 파일을 업데이트하여 스크롤을 위한 더 많은 콘텐츠를 포함합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Fixed Positioning Scroll Test</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="left-ad">
      <h3>Left Ad</h3>
      <p>I stay in place!</p>
    </div>

    <div class="right-ad">
      <h3>Right Ad</h3>
      <p>Always visible</p>
    </div>

    <div class="bottom-ad">
      <h3>Bottom Ad</h3>
      <p>Fixed at bottom</p>
    </div>

    <div class="content">
      <h1>Scrolling Behavior Demonstration</h1>

      <div class="scroll-content">
        <h2>Scroll Down to See Fixed Elements</h2>

        <!-- Create long content to enable scrolling -->
        <div class="long-content">
          <h3>Long Content Section</h3>
          <p>
            This section will allow you to scroll and observe how fixed-position
            elements remain in place.
          </p>

          <!-- Repeat paragraphs to create scrollable content -->
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in
            dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula.
          </p>

          <!-- Add multiple repetitions to create significant scroll length -->
          <p>
            Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor. Ut in
            nulla enim. Phasellus molestie magna non est bibendum non venenatis
            nisl tempor.
          </p>

          <!-- Repeat similar paragraphs multiple times -->
          <p>
            Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor
            posuere. Praesent id metus massa, ut blandit odio.
          </p>

          <!-- Continue adding paragraphs to create scroll effect -->
          <p>
            Proin quis tortor orci. Etiam at risus et justo dignissim congue.
            Donec congue lacinia dui, a porttitor lectus condimentum laoreet.
          </p>

          <!-- More paragraphs to extend scrolling -->
          <p>
            Nunc dignissim risus id metus. Cras ornare tristique elit. Vivamus
            vestibulum nulla sit amet tristique reprehenderit.
          </p>
        </div>
      </div>
    </div>
  </body>
</html>

스크롤 데모를 향상시키기 위해 styles.css를 업데이트합니다.

body {
  font-family: Arial, sans-serif;
  line-height: 1.6;
  margin: 0;
  padding: 0;
}

.content {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.long-content {
  background-color: #f9f9f9;
  padding: 20px;
}

/* Previous fixed positioning styles remain the same */

고정 위치 지정에 대한 주요 관찰 사항:

  • 고정 요소는 동일한 화면 위치에 유지됩니다.
  • 스크롤은 해당 위치에 영향을 미치지 않습니다.
  • 요소는 페이지 스크롤 위치에 관계없이 계속 표시됩니다.

예시 스크롤 동작:

  • 왼쪽, 오른쪽 및 하단 광고는 고정된 상태로 유지됩니다.
  • 콘텐츠는 고정 요소 뒤로 스크롤됩니다.
  • 고정 요소는 화면에서 항상 표시됩니다.

요약

이 랩에서는 CSS 의 고정 위치 지정 (fixed positioning) 에 대해 배웠습니다. 이는 페이지 스크롤에 관계없이 화면에서 요소가 고정된 상태로 유지되도록 하는 강력한 레이아웃 기술입니다. 개발자는 position: fixed 속성을 사용하여 사이드 광고 또는 탐색 메뉴와 같이 사용자가 콘텐츠를 스크롤할 때에도 계속 표시되는 일관된 위치에 있는 요소를 만들 수 있습니다.

이 랩은 학습자가 고정 위치 지정을 시연하는 실용적인 예제를 만드는 과정을 안내했습니다. 여기에는 HTML 프로젝트 구조 설정, top 및 right와 같은 CSS 속성을 적용하여 요소 배치를 정밀하게 제어하는 것이 포함되었습니다. 참가자들은 브라우저 창에 대한 참조 및 일정한 화면 위치를 유지하는 기능과 같은 고정 위치 지정의 주요 특징을 탐구하여 이 필수적인 CSS 레이아웃 기술에 대한 실질적인 경험을 얻었습니다.