소개:
웹사이트를 디자인하는 것은 예술 작품을 만드는 것과 같습니다. 그림의 배열이 이야기를 전달하는 것처럼 웹사이트의 레이아웃은 메시지에 대해 더 많은 것을 전달합니다. Flexbox는 이를 달성하기 위한 강력한 도구입니다.
Flexbox 이전에는 개발자가 반응형 디자인을 만들기 위해 플로팅 요소, 여백 해킹, 테이블 레이아웃과 같은 기술을 사용해야 했습니다. 이러한 방법은 효과가 있었지만 확장성이 없었고 다양한 화면 크기에 맞게 조정하려면 추가 미디어 쿼리가 필요했습니다.
Flexbox는 컨테이너 내의 요소를 정렬, 배포 및 크기 조정하는 간단하고 효율적인 방법을 제공하여 이러한 상황을 변화시켰습니다.
Flexbox란 무엇인가요?
Flexbox는 복잡한 레이아웃을 쉽게 만들 수 있도록 도와주는 레이아웃 모델입니다. 컨테이너 내에서 항목을 가로 또는 세로로 정렬할 수 있습니다. Flexbox는 1차원적입니다. 즉, 한 번에 단일 축(가로 또는 세로)을 따라 레이아웃을 제어합니다.
- 가로 정렬: 항목을 행별로 쉽게 정렬할 수 있습니다.
- 세로 정렬: 열의 항목을 정렬합니다.
이 블로그에서는 Flexbox의 주요 속성과 이를 통해 레이아웃 관리를 단순화하는 방법을 살펴보겠습니다.
Flex 컨테이너 속성:
Flex 속성을 살펴보기 전에 Flexbox의 두 축을 이해하는 것이 중요합니다.
- 주축
- 교차축
일부 속성은 기본 축을 따라 항목을 정렬하고 다른 속성은 교차 축을 따라 항목을 정렬하므로 이러한 축을 이해하는 것이 중요합니다. 이를 알면 속성의 작동 방식을 더 잘 이해하는 데 도움이 됩니다.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

자신의 코드를 리팩터링하는 것은 어떤 모습입니까? John Rhea는 자신이 쓴 오래된 CSS 애니메이션을 선택하고 최적화하는 사고 과정을 살펴 봅니다.

cssanimationsarenherinly에 hardbutreepracticenderstandingofcsspropertiesandtimingflestions.1) startsimpleants withsimpleatslikeScalingabuttononHoverusingKeyframes.2) useAsingfuctionslikecubic-bezierfornateffects, 그러한 분위기, 3)

@keyframesispopularduetoitstativerstatility 및 powerincreatingsmoothcssanimations.keytricksinclude : 1) states 사이에 moothtransitionsbettites, 2) 애니메이션 multiplepropertiessimultory, 3) vendorPixesforBrowsercompatibility, 4) 빗질을 사용하여

csScounterSearedTomanageAutomaticNumberingInberingInwebDesigns.1) 1) theCanbeusedfortablestoffContents, ListItems 및 CustomNumbering.2) AdvancedUsesInSinestedNumberingsystems.3) CreativeUseNvolvecust를 CreativeSinvolecust.4) CreativeSinvolvecust

특히 모바일 장치에 스크롤 그림자를 사용하는 것은 Chris가 이전에 다룬 미묘한 UX입니다. Geoff는 애니메이션 타임 라인 속성을 사용하는 새로운 접근 방식을 다루었습니다. 또 다른 방법이 있습니다.

빠른 새로 고침을 통해 실행합시다. 이미지 맵은 html 3.2로 돌아가는데, 먼저 서버 측 맵과 클라이언트 측지 맵은 맵 및 영역 요소를 사용하여 이미지를 통해 클릭 가능한 영역을 정의했습니다.

Devs State Survey는 이제 참여에 개방되어 있으며, 이전 설문 조사와 달리 코드, 직장, 건강, 취미 등을 제외한 모든 것을 포함합니다.

CSS 그리드는 복잡하고 반응이 좋은 웹 레이아웃을 만드는 강력한 도구입니다. 디자인을 단순화하고 접근성을 향상 시키며 이전 방법보다 더 많은 제어를 제공합니다.


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.