Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS로 반응형 이미지 갤러리 만드는 방법 (미디어 쿼리 예제 코드 포함)

CSS로 반응형 이미지 갤러리 만드는 방법

반응형(Responsive) 이미지 갤러리는 방문자가 데스크톱, 태블릿, 스마트폰 등 어떤 기기를 사용하든 화면 너비에 맞춰 이미지 배치가 자동으로 재조정되는 갤러리를 말합니다. CSS의 미디어 쿼리(@media)float 속성만 활용하면 JavaScript 없이도 손쉽게 구현할 수 있습니다.

핵심 구현 원리

이번 예제에서 사용하는 핵심 기술은 다음과 같습니다.

  • float: left — 각 갤러리 항목을 나란히 배치합니다.
  • width: 24.99999% — 한 줄에 4개의 이미지가 들어가도록 설정합니다.
  • @media 쿼리 — 화면 너비가 700px 이하면 2열, 500px 이하면 1열로 전환합니다.
  • clearfix — float 요소로 인한 레이아웃 무너짐을 방지합니다.
  • width: 100%; height: auto — 이미지가 부모 요소 너비에 맞춰 원본 비율을 유지하며 확대·축소됩니다.

전체 예제 코드

아래 코드를 그대로 복사해 HTML 파일로 저장한 뒤 브라우저에서 열고, 창 크기를 조절해 보세요. 화면 폭에 따라 갤러리가 4열 → 2열 → 1열로 변하는 것을 바로 확인할 수 있습니다.

<!DOCTYPE html>
<html>
  <head>
    <style>
      div.myGallery {
        border: 2px solid orange;
      }
      div.myGallery:hover {
        border: 1px solid blue;
      }
      div.myGallery img {
        width: 100%;
        height: auto;
      }
      div.desc {
        padding: 20px;
        text-align: center;
      }
      .responsive {
        padding: 0 5px;
        float: left;
        width: 24.99999%;
      }
      @media only screen and (max-width: 700px) {
        .responsive {
          width: 49.99999%;
          margin: 5px 0;
        }
      }
      @media only screen and (max-width: 500px) {
        .responsive {
          width: 100%;
        }
      }
      .clearfix:after {
        content: "";
        display: table;
        clear: both;
      }
    </style>
  </head>
  <body>
    <div class="responsive">
      <div class="myGallery">
        <a target="_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg">
          <img src="https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg" alt="3D Animation Tutorial" width="600" height="500">
        </a>
        <div class="desc">3D 애니메이션 튜토리얼</div>
      </div>
    </div>
    <div class="responsive">
      <div class="myGallery">
        <a target="_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg">
          <img src="https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg" alt="Swift Video Tutorial" width="600" height="500">
        </a>
        <div class="desc">Swift 영상 튜토리얼</div>
      </div>
    </div>
    <div class="responsive">
      <div class="myGallery">
        <a target="_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg">
          <img src="https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg" alt="CSS Video Tutorial" width="600" height="500">
        </a>
        <div class="desc">CSS 튜토리얼</div>
      </div>
    </div>
    <div class="clearfix"></div>
  </body>
</html>

코드 상세 설명

1. 갤러리 카드 스타일링

.myGallery는 각 이미지를 감싸는 카드 역할을 합니다. 평소에는 주황색 2px 테두리가 표시되고, 마우스를 올리면(:hover) 파란색 1px 테두리로 바뀌며 시각적인 피드백을 제공합니다. 내부 img에는 width: 100%height: auto를 적용해 카드 너비에 맞춰 비율이 유지된 채 유연하게 크기가 조절됩니다.

2. 반응형 열 배치

.responsive 클래스가 실제 반응형의 핵심입니다. 기본 상태에서는 width: 24.99999%로 한 줄에 4개씩 배치되고, float: left 덕분에 좌측부터 차례로 나열됩니다. 25%가 아닌 24.99999%를 사용하는 이유는 일부 브라우저의 소수점 반올림 오차로 인해 마지막 항목이 아래 줄로 밀려나는 현상을 방지하기 위해서입니다.

3. 미디어 쿼리로 화면 크기 대응

  • 화면 너비가 700px 이하일 때 → width: 49.99999%로 변경되어 한 줄에 2개씩 표시됩니다.
  • 화면 너비가 500px 이하일 때 → width: 100%로 변경되어 한 줄에 1개씩 세로로 쌓입니다.

4. clearfix로 레이아웃 정리

float된 요소는 부모 컨테이너의 높이 계산에서 제외되기 때문에, 그대로 두면 다음 콘텐츠가 갤러리와 겹칠 수 있습니다. .clearfix:afterdisplay: tableclear: both를 지정하면 float의 영향을 깔끔하게 해제할 수 있습니다.

참고: 더 현대적인 방법 — Flexbox와 Grid

float 기반 기법은 브라우저 호환성이 뛰어나지만, 최신 프로젝트에서는 Flexbox나 CSS Grid를 사용하는 것이 유지보수 측면에서 더 유리합니다. 특히 Grid의 repeat(auto-fill, minmax(250px, 1fr)) 한 줄이면 위 예제와 동일한 반응형 배치를 훨씬 간결하게 구현할 수 있으니, 기본기를 익힌 후 꼭 비교해 보시길 권합니다.

마무리

미디어 쿼리의 중단점(breakpoint)인 700px, 500px 값은 프로젝트 성격에 맞게 자유롭게 조정할 수 있습니다. 위 코드에 hover 시 그림자 효과 추가, 이미지 개수 확장, 캡션 디자인 변경 등을 적용해 보면 반응형 웹 제작 감각을 키우는 데 큰 도움이 될 것입니다.