이전에 많이 사용하던 display: inline-block, float: left와 더불어 요소의 가로배치에 많이 사용되는 방법으로 브라우저 호환성은 아래와 같다. 기존의 방법에 비해 매우 간편하여, 최근 많이 사용됨

 

<!DOCTYPE html>
<html>
<head>
  <title>Document</title>
  <link rel="stylesheet" href="css/flex.css">
</head>
<body>
  <div class="container">
    <div class="item">AAA</div>
    <div class="item">B</div>
    <div class="item">CCCCCC</div>
    <div class="item">DDD</div>
    <div class="item">EEE</div>
  </div>
</body>
</html>

1. 부모 요소 flex

.container {  
  display: flex;  
  flex-direction: row;
  /* flex-direction: column; */

  justify-content: flex-start;
  /* justify-content: center; */
  /* justify-content: space-between; */
  /* justify-content: space-around; */
 
  align-items: stretch;
  /* align-items: center; */
  height: 80vh;
  background: gray;
}
.item {
  border: 1px solid black;
  background: white;
  font-size: 4em;
}

- 부모요소(.container)에 display: flex;지정

1) flex-direction: 자식 요소들을 정렬할 축을 지정 (row, column + reverse)

2) justify-content : 축에서의 요소 정렬 방법 (flex-start/end, center, space-between/around)

flex-direction: row; + 

3) align-items : 축의 위치를 정렬 (flex-start/end, center, stretch, baseline)

flex-direction: row; + 

* justify-content: center;  +  align-items: center;   =>  화면 중앙 정렬

 


2. 자식요소 flex

- 화면크기 변화에 따라 자식 요소의 크기를 유연하게 조정

- flex-grow: 숫자; 자식요소들이 축 방향에서 차지하는 비율을 조정 (요소의 width를 조정하는 것이 라니라, 콘텐츠의 너비를 제외한 여백을 조절하여 공간을 나눠가지게 함)

- 자식요소들이 부모의 공간을 모두 차지

- 일괄적용 : flow-grow: 아무 숫자;

- 개별 적용 : flow-grow: 해당 요소가 공간을 차지할 비율;

- flex-basis: 0;으로 지정하여 콘텐츠를 제외한 여백 대신, 요소 자체의 크기를 조절하게 해줌, 기본값은 auto

- flex: 1; = flex-grow: 1; + flex-basis: 0; + flex-shrink: 1;

.item {    
  /* flex-grow: 1;
  flex-basis: 0; */
  flex : 1;  
  border: 1px solid black;
  background: white;  
}
/* 
.item:nth-child(1) {flex-grow: 1}
.item:nth-child(2) {flex-grow: 5}
.item:nth-child(3) {flex-grow: 2}
.item:nth-child(4) {flex-grow: 3}
.item:nth-child(5) {flex-grow: 1} 
*/

'WEB > css' 카테고리의 다른 글

[CSS] position  (0) 2020.04.12
[CSS] 가로배치방법 (display: inline-block, float: left)  (0) 2020.04.12