상세 컨텐츠

본문 제목

[CSS] flex로 원하는 요소를 크기가 다른 요소들의 중앙에 배치하기

CSS

by spring92 2021. 4. 29. 18:23

본문

하나의 row에 정사각형의 box 세 개 만들어서 space-between으로 정렬했을 시

<div class="row">
	<div class="box1"></div>
	<div class="box2"></div>
	<div class="box3"></div>
</div>
.row {
  width: 500px;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid black;
}

.box1 {
  width: 50px;
  height: 50px;
  background-color: red;
}

.box2 {
  width: 50px;
  height: 50px;
  background-color: blue;
}

.box3 {
  width: 50px;
  height: 50px;
  background-color: green;
}

 

두번째 박스는 row의 정확히 가운데에 오게 된다. 하지만 각 box의 크기가 달라지면

.box1 {
  width: 150px;
  height: 50px;
  background-color: red;
}

.box2 {
  width: 50px;
  height: 50px;
  background-color: blue;
}

.box3 {
  width: 30px;
  height: 50px;
  background-color: green;
}

두번째 box는 오른쪽으로 치우치게 된다. 이때, 두번째 box를 정확히 가운데로 오게 하려면 

<div class="row">
	<div class="column">
		<div class="box1"></div>
	</div>
	<div class="column">
		<div class="box2"></div>
	</div>
	<div class="column">
		<div class="box3"></div>
	</div>
</div>
.column{
  width:33%
}

.column:nth-child(2){
display: flex;
justify-content: center;
}

.column:last-child{
  display: flex;
  justify-content: flex-end;
}

각 box를 column이라는 div 안에 넣고 column에 33%의 width를 준 다음

두번째 box에 justify-content: center,

마지막 box에 justify-content: flex-end를 주면

이렇게 두번째 box가 row의 정확히 가운데에 위치하게 된다.

 

+) 추가

column {

flex: 1;

text-align: center;

}

으로도 가능하다.

 

flex가 아니라 grid로도 가능하다.

.row{

display: grid;

grid-template-column: repeat(3 1fr)

}

.column {

text-align: center;

}

관련글 더보기