Notice
Recent Posts
Recent Comments
관리 메뉴

즐겁게, 코드

CSS order 속성으로 요소 순서 제어하기 본문

🎨 프론트엔드/HTML & CSS

CSS order 속성으로 요소 순서 제어하기

Chamming2 2021. 8. 29. 02:11

귀여운 고양이들이 지그재그로 위치한 모습입니다!

flexbox가 적용된 컨테이너 안에 left-, right- 요소가 있고, 각 요소 안에 사진과 설명이 적절히 들어간 레이아웃입니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <article class="flex-container">
      <div class="left-1">
        <img src="cat1.jpeg" alt="cat1" />
      </div>
      <div class="right-1">
        <p>1번 고양이입니다.</p>
      </div>
    </article>
    <article class="flex-container">
      <div class="left-2">
        <p>2번 고양이입니다.</p>
      </div>
      <div class="right-2">
        <img src="cat2.png" alt="cat2" />
      </div>
    </article>
    <article class="flex-container">
      <div class="left-3">
        <img src="cat3.jpeg" alt="cat3" />
      </div>
      <div class="right-3">
        <p>3번 고양이입니다.</p>
      </div>
    </article>
  </body>
</html>
img {
  width: 200px;
}

.flex-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border: 1px solid #cdcdcd;
}

@media (max-width: 768px) {
  .flex-container {
    display: flex;
    flex-direction: column;
  }
}

css는 컨테이너에 flex 속성을 적용하고, 작은 화면에서는 아이템 내 요소가 세로로 보이도록 미디어쿼리를 추가한 모습입니다.
그런데, 화면을 축소하면 두 번째 고양이 아이템에 작은 문제가 생깁니다.

<article class="flex-container">
  <div class="left-2">
    <p>2번 고양이입니다.</p>
  </div>
  <div class="right-2">
    <img src="cat2.png" alt="cat2" />
  </div>
</article>

마크업상 left 요소가 right 요소보다 위에 있기 때문에 레이아웃을 세로로 변경하면 left 요소가 right 요소 위에 오게 되는데요, 이러면 고양이의 설명이 사진 위에 오게 됩니다.

이런 상황에서는 order 속성을 유용하게 활용할 수 있습니다.

order 속성

order 는 동일한 컨테이너에서 요소의 순서를 결정하는 속성입니다.

<article class="flex-container">
  <div class="left-2">
    <p>2번 고양이입니다.</p>
  </div>
  <div class="right-2">
    <img src="cat2.png" alt="cat2" />
  </div>
</article>

현재 2번 고양이 아이템의 왼쪽 요소를 의미하는 left-2 는 컨테이너의 첫 번째 요소이며 right-2 는 컨테이너의 두 번째 요소이므로, 이는 CSS로 이렇게 나타낼 수 있는 상황입니다.

.left-2 {
    order: 1;
}
.right-2 {
    order: 2;
}

대략 감이 오지 않나요?

이제 미디어쿼리를 수정해, left-2right-2 의 배치 순서를 변경해 보겠습니다.

.left-2 {
  order: 1;
}
.right-2 {
  order: 2;
}

@media (max-width: 768px) {
  .left-2 {
    order: 2;
  }
  .right-2 {
    order: 1;
  }
}

이제 원하던 대로 고양이의 사진이 위, 설명이 아래에 위치하는 모습입니다.

 

order 속성을 사용해 원하는 대로 요소의 순서를 변경할 수 있었는데요, 이를 너무 남용하면 마크업의 직관성을 해칠 수 있으니 위의 상황처럼 꼭 필요한 상황에서만 사용하는 것이 권장된다고 합니다. 😁

반응형
Comments
소소한 팁 : 광고를 눌러주시면, 제가 뮤지컬을 마음껏 보러다닐 수 있어요!
와!! 바로 눌러야겠네요! 😆