data life

CSS - flex-grow, flex-shrink 본문

CSS/Flexbox

CSS - flex-grow, flex-shrink

주술회전목마 2022. 11. 16. 23:01

flex-grow

남는 행의 여백을 나눠서 채우는 방법으로
flex-grow 속성이 적용되지 않거나 속성 값이 0 인 경우

레이아웃 너비보다 item들의 너비 합이 더 작으면 아이템 우측 끝에 여백이 남게 된다.

HTML

<div class="layout">
    <div class="flex_box">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
    </div>
</div>

css

.flex_box{
    display: flex;
    flex-wrap: nowrap;
    gap: 0;
    padding: 10px;
    background-color: #e8e8e8;
}
.item{
    min-height: 150px;
    flex-basis: 100px;
}
.item:nth-child(1){
	background-color:beige;
}
.item:nth-child(2){
	background-color: yellowgreen;
}
.item:nth-child(3){
	background-color: green;
 }
1
2
3

flex-grow 추가

.item:nth-child(1){
	background-color:beige;
    flex-grow: 1;
}
.item:nth-child(2){
	background-color: yellowgreen;
    flex-grow: 0;
}
.item:nth-child(3){
	background-color: green;
    flex-grow: 2;
 }
1
2
3
남는 공간의 여백 = 280px
** padding(20px)는 제외
280 / 3 = 93.33px
원래 너비였던 100px에서 부터 순서대로 193.33px, 100px, 286.66px 이다.

flex-shrink

flex-wrap 속성을 nowrap 으로 부여할 때 적용 가능하며
이때, 레이아웃 width를 넘을 겨우 끝에 걸치는 아이템은 다음 행의 다시 배치되어 레이아웃 영역을 넘지 않는다.
>> default :1 속성을 정의하지 않고 자동으로 item 이 축소되어 적용

>> flex-shrink : 0; 이면 자동으로 width가 축소되지 않음

 

HTML

<body>
	<div class="layout">
    	<div class="father">
        	<div class="child">1</div>
        	<div class="child">2</div>
        	<div class="child">3</div>
    	</div>
	</div>
</body>

CSS

.child:nth-child(1){flex-shrink: 1;}
.child:nth-child(2){flex-shrink: 0;}
.child:nth-child(3){flex-shrink: 2;}
1
2
3

 

 

CSS

.layout {
    max-width: 500px;
    marin:0 auto;
    padding:0;
}
.father {
    display: flex;
    flex-wrap: nowrap;
    padding:10px;
    background-color: #f0f0f0;
}
.child {
    min-height: 130px;
    flex-basis: 200px; // 늘어나거나(grow) 찌그러지기(shrink) 전에 요소의 width 설정
    flex-shrink: 0;   // 아이템 축소 불가
    border : 3px solid white;
}

.child:nth-child(1),
.child:nth-child(3){
    background-color: beige;
}
.child:nth-child(2) {
    background-color: yellowgreen;
}
1
2
3
flex-shrink 속성 값의 합 = 1 + 0 + 2 = 3
넘어간 너비는 패딩공간 포함하여 220px
따라서, 220px / 3 = 76.6666..px = flex-shrink의 속성값 1
각 너비는 123.33px, 200px, 46.66px 이다.