Elements 가운데 정렬
<div>와 같은 “Block” Element에 width가 설정돼있는 경우 margin: auto; 를 사용해 수평으로 가운데 정렬 할 수 있다.
.center {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
참고: width 속성이 설정되어 있지 않거나 100%로 설정되어 있으면 가운데 정렬되지 않음.
Text 가운데 정렬
Text Element는 text-align: center; 를 사용해 수평으로 가운데 정렬 할 수 있다.
.center {
text-align: center;
border: 3px solid green;
}
Image 가운데 정렬
Image는 왼쪽, 오른쪽 margin을 auto로 설정하고 display: block; 으로 설정하면 된다.
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
좌/우측 정렬 — Using position
position: absolute; 설정 후 right 또는 left 값을 0으로 설정해 좌/우측 정렬할 수 있다.
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
참고: absolute로 설정한 element는 정상 흐름에서 제거되어 다른 element와 겹칠 수 있다.
좌/우측 정렬 — Using float
float: right; 또는 float: left 속성을 사용해 좌/우측 정렬할 수 있다.
.right {
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
참고: float이 설정된 element는 말 그대로 붕 “떠 있는” 상태로 그 크기가 상위 컨테이너 element보다 클 경우 컨테이너 밖으로 overflow 되어 보인다. 이는 “clearfix” hack을 통해 해결할 수 있다.
수직으로 가운데 정렬 — Using padding
padding 값으로 top, bottom에 여유공간을 주어 수직으로 가운데 정렬할 수 있다.
.center {
padding: 70px 0;
border: 3px solid green;
}
수직으로 가운데 정렬 — Using line-height
height와 line-height 값을 동일하게 설정하는 트릭으로 가운데 정렬할 수도 있다.
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
/* If the text has multiple lines, add the following: */
.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
수직으로 가운데 정렬 — Using position & transform
position: absolute; 로 설정해 부모 element로부터 top: 50% 떨어진 후 자신의 height의 50% 만큼 위로 올라가면 수직으로 가운데 정렬 된다.
.center {
height: 200px;
position: relative;
border: 3px solid green;
}
.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}