찾다

CSS의 Flex 속성 이해

Sep 12, 2024 am 10:16 AM

소개:

웹사이트를 디자인하는 것은 예술 작품을 만드는 것과 같습니다. 그림의 배열이 이야기를 전달하는 것처럼 웹사이트의 레이아웃은 메시지에 대해 더 많은 것을 전달합니다. Flexbox는 이를 달성하기 위한 강력한 도구입니다.

Flexbox 이전에는 개발자가 반응형 디자인을 만들기 위해 플로팅 요소, 여백 해킹, 테이블 레이아웃과 같은 기술을 사용해야 했습니다. 이러한 방법은 효과가 있었지만 확장성이 없었고 다양한 화면 크기에 맞게 조정하려면 추가 미디어 쿼리가 필요했습니다.

Flexbox는 컨테이너 내의 요소를 정렬, 배포 및 크기 조정하는 간단하고 효율적인 방법을 제공하여 이러한 상황을 변화시켰습니다.

Flexbox란 무엇인가요?

Flexbox는 복잡한 레이아웃을 쉽게 만들 수 있도록 도와주는 레이아웃 모델입니다. 컨테이너 내에서 항목을 가로 또는 세로로 정렬할 수 있습니다. Flexbox는 1차원적입니다. 즉, 한 번에 단일 축(가로 또는 세로)을 따라 레이아웃을 제어합니다.

  1. 가로 정렬: 항목을 행별로 쉽게 정렬할 수 있습니다.
  2. 세로 정렬: 열의 항목을 정렬합니다.

이 블로그에서는 Flexbox의 주요 속성과 이를 통해 레이아웃 관리를 단순화하는 방법을 살펴보겠습니다.

Flex 컨테이너 속성:

Flex 속성을 살펴보기 전에 Flexbox의 두 축을 이해하는 것이 중요합니다.

  1. 주축
  2. 교차축

일부 속성은 기본 축을 따라 항목을 정렬하고 다른 속성은 교차 축을 따라 항목을 정렬하므로 이러한 축을 이해하는 것이 중요합니다. 이를 알면 속성의 작동 방식을 더 잘 이해하는 데 도움이 됩니다.

Understanding Flex Properties in CSS

flex-direction: 행 | 칼럼

Flexbox는 항목을 행이나 열로 정렬하는 것입니다. 기본적으로 행으로 설정되어 있습니다.

  • : 항목을 가로로 정렬합니다(기본값).
  • : 항목을 수직으로 정렬합니다.
<div style="display: flex; flex-direction: row;">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</div>

flex-wrap: nowrap | 랩 | 랩 리버스

플렉스 항목을 축소하는 대신 다음 줄로 줄 바꿈할 수 있습니다. 기본값은 nowrap입니다.

  • nowrap: 모든 플렉스 항목이 한 줄에 표시됩니다(기본값).
  • wrap: Flex 항목이 맞지 않으면 다음 줄로 줄 바꿈됩니다.
  • wrap-reverse: Flex 항목이 반대 방향으로 래핑됩니다.
<div style="display: flex; flex-wrap: wrap;">
  <div class="box">Item 1</div>
  <div class="box">Item 2</div>
  <div class="box">Item 3</div>
</div>

정의 콘텐츠: flex-start | 플렉스엔드 | 센터 | 공백 사이 | 우주 주위 | 공간 균등

주축을 따라 항목을 정렬하는 데 사용됩니다. flex-direction: row의 경우 x축은 주축이고 y축은 교차축입니다.

  • flex-start: 항목을 컨테이너 시작 부분에 정렬합니다.
  • flex-end: 항목을 끝에 정렬합니다.
  • center: 항목을 중심으로 합니다.
  • space-between: 아이템 사이에 공백을 두고 배치합니다.
  • space-around: 주변에 공간을 두고 아이템을 배포합니다.
  • space-evenly: 항목 사이의 공간을 균등하게 분배합니다.
<div style="display: flex; justify-content: space-between;">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</div>

항목 정렬: 플렉스 시작 | 플렉스엔드 | 센터 | 스트레칭 | 기준

교차축을 따라 항목을 정렬하는 데 사용됩니다. 열 flex-direction의 경우 y축이 주축이고 x축이 교차축입니다.

  • flex-start: 항목을 교차축의 시작 부분에 정렬합니다.
  • flex-end: 항목을 끝에 정렬합니다.
  • center: 교차축의 중심에 항목을 배치합니다.
  • 늘이기: 항목을 늘려 컨테이너를 채웁니다.
  • 기준선: 텍스트 기준선을 기준으로 항목을 정렬합니다.
<div style="display: flex; align-items: center; height: 200px;">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</div>

Flex 항목 속성

align-self: flex-start | 플렉스엔드 | 센터 | 스트레칭 | 기준
align-self 속성을 사용하면 교차축을 따라 개별 하위 항목을 정렬
할 수 있습니다.

<div style="display: flex; height: 200px;">
  <div style="align-self: flex-start;">Item 1</div>
  <div style="align-self: center;">Item 2</div>
  <div style="align-self: flex-end;">Item 3</div>
</div>

성장과 축소
알아야 할 3가지 속성: flex-grow, flex-shrink 및 flex-basis.

플렉스 성장:

This property defines how much a flex item will grow relative to the other items inside a flex container when there is extra space available. By default, flex-grow is set to 0, meaning items won't grow beyond their natural size. Setting flex-grow: 1 allows the item to expand and occupy the remaining available space within the container.

If multiple items have flex-grow:1 applied, they will divide the extra space proportionally, based on the grow values set for each item.

Imagine a dashboard layout where you have a sidebar and a main content area. You want the sidebar to stay fixed in size, but the main content area should expand and take up the remaining space.

<div style="display: flex;">
  <div style="flex-grow: 0; width: 200px;">Sidebar</div> <!-- Fixed width sidebar -->
  <div style="flex-grow: 1;">Main Content Area</div> <!-- Expanding content area -->
</div>

flex-shrink:

When the container size reduces, items inside will also shrink proportionally.

For example, consider a profile card with a rounded image and a name. As the container shrinks, the image may distort, turning from a circle to an oval. To prevent this, you can set flex-shrink: 0, ensuring the image retains its original size while the rest of the content adapts.

<div style="display: flex;">
  <img src="/static/imghwm/default1.png" data-src="profile.jpg" class="lazy"   style="max-width:90%" alt="Profile Picture"> <!-- Image won't shrink -->
  <div style="flex-shrink: 1;">User Name</div> <!-- Name can shrink -->
</div>

While you might think of using min-width to achieve the same effect, flex-shrink is a more straightforward and flexible approach within the Flexbox algorithm.

  • flex-grow controls how extra space is distributed among items.
  • flex-shrink controls how space is reduced when the container size decreases.

flex-basis: Setting the Initial Size

The flex-basis property defines the initial size of a flex item. If the flex-direction is set to row, flex-basis controls the width of the items. If the flex-direction is column, it controls the height.

flex-basis is similar to the width or height properties, but with one key difference: it only sets the initial size, while allowing the item to grow or shrink depending on the available space and the flex-grow and flex-shrink values.

  • If flex-basis is set to auto or content, the size of the item is based on its content.
  • If you want to define a fixed starting size but still allow the item to grow or shrink, use flex-basis.
.child {
  flex-basis: 25%;  /* Starts at 25% width, but can grow to fill space */
  flex-grow: 1;     /* Will grow to take up more space if available */
}

In this example, the child element initially takes up 25% of the container’s width, but it can grow beyond that if there’s more space available.

Setting a fixed size:

If you want the item to have a fixed size (not grow or shrink), you can use the flex shorthand, like this:

.child {
  flex: 0 0 100px; /* No growth, no shrinking, stays fixed at 100px */
}

This shorthand breaks down as:

  • 0 (flex-grow): The item will not grow.
  • 0 (flex-shrink): The item will not shrink.
  • 100px (flex-basis): The item has a fixed size of 100px.

Using width instead of flex-basis inside a flex layout can lead to issues sometimes.because the item defined with width and won't adjust if the container grows or shrinks, making the layout less responsive. So use it appropriately.

align-content:

We've already learned about flex-wrap. Flex-wrap allows flex items to wrap to the next lines instead of shrinking, right?

Each of these flex lines acts like a separate "mini flex container". We also know that the align-items property is used to align items on the cross axis. Here, this align-items property will work inside this flex line only, because as I mentioned, each line itself is a mini flex container. We also have an outer flex container, right? If we need to align these lines with respect to the outer container, we need one more property that aligns these flex lines on the cross axis. That property is align-content.

.container {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  height: 300px;
}

.item {
  width: 30%;
  height: 50px;
  background-color: #3498db;
  margin: 5px;
}

In this example, we have a flex container with multiple items that wrap onto multiple lines. The align-content: center; property centers the wrapped lines along the container's cross-axis.

The possible values for align-content include:

  • flex-start: Lines are aligned toward the start of the container.
  • flex-end: Lines are aligned toward the end of the container.
  • center: Lines are centered in the container.
  • space-between: Lines are evenly distributed; the first line is at the start of the container while the last one is at the end.
  • space-around: Lines are evenly distributed with equal space around each line.
  • stretch (default): Lines stretch to take up the remaining space.

Gaps

The gap property was not available in earlier versions of Flexbox. Previously, developers relied on margin properties to create space between flex items. The introduction of the gap property marked a significant improvement in Flexbox functionality.

It provides a straightforward method for creating space between flex items, simplifying the layout process.

.flex-container {
  display: flex;
  gap: 10px; /* Adds a 10px gap between all flex items */
}

Auto margins

margin: auto:

Last but not least, a commonly used spacing trick

The margin: auto property in Flexbox is a powerful tool for aligning flex items. It automatically uses the leftover space around the item, making it useful for centering or pushing items to opposite sides of a container.

For example, you can use margin-left: auto to push an item to the right side of a flex container:

.flex-container {
  display: flex;
}

.push-right {
  margin-left: auto;
}

This technique allows for quick and easy alignment without the need for additional positioning properties.

Conclusion

In this guide, we explored how Flexbox has simplified the task of aligning and distributing items within a webpage. Flexbox isn't just a layout tool—it's a critical skill for any web developer aiming to create responsive, well-structured designs. I hope this guide has helped you understand the power of Flexbox.

Try these demos and feel free to share your thoughts or questions. Thanks!

위 내용은 CSS의 Flex 속성 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
드래그 ' 및 Droppin ' 반응에서드래그 ' 및 Droppin ' 반응에서Apr 17, 2025 am 11:52 AM

React Ecosystem은 모두 드래그 앤 드롭의 상호 작용에 중점을 둔 많은 라이브러리를 제공합니다. 우리는 React-dnd, React-beautiful-dnd를 가지고 있습니다.

빠른 소프트웨어빠른 소프트웨어Apr 17, 2025 am 11:49 AM

최근 빠른 소프트웨어에 대해 놀랍도록 상호 연결된 것들이있었습니다.

배경 클립이있는 중첩 된 그라디언트배경 클립이있는 중첩 된 그라디언트Apr 17, 2025 am 11:47 AM

나는 자주 배경 클립을 사용한다고 말할 수 없습니다. I ' D WART IT IT는 일상적인 CSS 작업에서 거의 사용되지 않았습니다. 그러나 나는 Stefan Judis의 게시물에서 그것을 상기시켰다.

React 후크와 함께 requestAnimationFrame 사용React 후크와 함께 requestAnimationFrame 사용Apr 17, 2025 am 11:46 AM

requestAnimationFrame을 사용하여 애니메이션은 쉬워야하지만 React의 문서를 철저히 읽지 않으면 몇 가지 문제가 발생할 수 있습니다.

페이지 상단으로 스크롤해야합니까?페이지 상단으로 스크롤해야합니까?Apr 17, 2025 am 11:45 AM

아마도이를 사용자에게 제공하는 가장 쉬운 방법은 요소의 ID를 대상으로하는 링크 일 것입니다. 그래서 ...처럼 ...

최고 (GraphQL) API는 귀하가 작성한 것입니다최고 (GraphQL) API는 귀하가 작성한 것입니다Apr 17, 2025 am 11:36 AM

들어보세요, 나는 GraphQL 전문가가 아니지만 함께 일하는 것을 좋아합니다. 프론트 엔드 개발자로서 데이터를 노출시키는 방법은 꽤 멋지다. 메뉴와 같습니다

주간 플랫폼 뉴스 : 텍스트 간격 북마크, 최상위 차단, 새로운 앰프 로딩 표시기주간 플랫폼 뉴스 : 텍스트 간격 북마크, 최상위 차단, 새로운 앰프 로딩 표시기Apr 17, 2025 am 11:26 AM

이번 주에 타이포그래피를 검사하기위한 편리한 북마크 인 Roundup, JavaScript 모듈과 Facebook의 Facebook 등을 어떻게 가져 오는지 땜질하기 위해 대기하는 편리한 북마크 인 Roundup과 Facebook의

테두리 반경을 보존하는 동안 상자를 확장하는 다양한 방법테두리 반경을 보존하는 동안 상자를 확장하는 다양한 방법Apr 17, 2025 am 11:19 AM

나는 최근 코데 펜에서 흥미로운 변화를 발견했다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.