프론트엔드/HTML & CSS & Javascript
CSS | 중앙 정렬 : 수평 중앙 정렬, 수직 중앙 정렬
YUNI Heo
2024. 5. 16. 10:41
반응형
⭕ CSS | 중앙 정렬 : 수평 중앙 정렬, 수직 중앙 정렬
➡️ 수평 중앙 정렬
inline / inline-block 요소
- inline 또는 inline-block 요소는 텍스트의 흐름을 따라 배치됨
- 부모 요소가 block 요소인 경우 text-align: center; 속성을 설정함
.parent {
text-align: center;
}
.child {
display: inline-block; /* 또는 inline */
}
block 요소
- 일반적인 설정
- block 요소는 기본적으로 전체 가용 너비를 차지함
- width 속성을 설정하고, 좌우 마진을 auto로 지정함
.block {
width: 200px; /* 너비 지정 */
margin: 0 auto; /* 위 아래 마진 0, 좌우 마진 auto */
}
- 이미지 요소 설정
- inline 요소(베이스라인을 기준으로 공간을 차지함)로 취급되지만, display: block;을 설정함으로써 block 요소처럼 동작함
img {
display: block;
width: 200px;
margin: 0 auto;
}
Flex 속성 사용
- display: flex;와 flex-direction: center;을 설정하여 부모 요소를 flex 컨테이너로 설정함
.parent {
display: flex;
justify-content: center;
}
➡️ 수직 중앙 정렬
inline / inline-block 요소
- 한 줄의 요소
- block 요소처럼 다루기 위해 display: block;을 설정함
- 요소의 높이(height)와 줄 높이(line-height)를 동일하게 설정하여 텍스트를 수직 중앙으로 맞춤
- white-space: nowrap; 속성은 텍스트가 줄 바뀜 없이 한 줄로 표시되도록 함
.single-line {
display: block;
height: 100px;
line-height: 100px;
white-space: nowrap;
}
- 여러 줄의 요소
- 부모 요소를 **display: table;**로, 자식 요소를 display: table-cell;로 설정하여 테이블 셀처럼 작동하게 함
.center {
display: table;
}
.center span {
display: table-cell;
vertical-align: middle;
}
block 요소
- 자식 요소의 높이 고정
- 부모 요소에 position: relative;를, 자식 요소에 position: absolute; 및 top: 50%;를 설정함
- 자식 요소를 자신의 높이의 절반만큼 상단으로 이동시키기 위해, margin-top을 음수 값으로 설정함
.parent {
position: relative;
height: 300px; /* 필요에 따라 설정 */
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* 높이의 절반 */
}
- 자식 요소의 높이 auto
- 자식 요소의 실제 높이의 절반만큼 위로 이동시키기 위해. transform: translateY(-50%);를 사용함
.parent {
position: relative;
height: 300px; /* 필요에 따라 설정 */
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Flex 속성 사용
- display: flex;와 flex-direction: column;을 설정하여 부모 요소를 flex 컨테이너로 설정함
.parent {
display: flex;
height: 300px; /* 필요에 따라 설정 */
flex-direction: column;
justify-content: center;
}
반응형