본문 바로가기
Front-end

[HTML/CSS] float:left 속성 없이 각 요소를 양측 끝에 정렬하기 - flex

by 셀킴 2022. 11. 28.
728x90

 

display:flex 속성을 이용하면

요소에 복잡하게 float:left, float:right을 각각 적용 후 부모 태그에 clear:both를 적용하는 등 수고를 하지않아도 된다.

 

특정 태그 내에 좌측, 우측으로 요소를 배치할 경우 float 대신

display:flex; justify-content:space-between;을 이용하면 간편하다.

주의할 점: justify-content:space-between;는 태그 내의 자식요소들을 양쪽 끝을 기준으로 동일한 여백으로 정렬하기때문에 아래 코드펜 예시처럼 한쪽에 여러 요소가 들어가는 경우에는 하나의 요소로 감싸야한다.

감싸지않는 경우에는 각 태그가 개별적으로 정렬됨

 

See the Pen Display:flex;justify-content:space-between; by nah (@wimmwell) on CodePen.

 

display:flex 속성을 사용해도 호환성 이슈는 거의 없다고 보면 된다.

나는 float는 거의 사용하지않고 display:flex로 요소 정렬을 한다.

 

 justfiy-content  속성 자세히 보기↓

https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content

 

justify-content - CSS: Cascading Style Sheets | MDN

The CSS justify-content property defines how the browser distributes space between and around content items along the main-axis of a flex container, and the inline axis of a grid container.

developer.mozilla.org

 

 

 

위 코드에는 없지만 flex 요소에 margin을 주는 속성인 gap, column-gap 또는 row-gap은 지원되지 않는 제법 있어서, 사용자 층이 다양한 웹사이트의 경우에는 gap 속성보다는 margin으로 여백을 주는 것이 낫다고 생각한다.

 

728x90