CSS 정렬마스터가 되고싶다..(꒦ິ⌓꒦ີ).. 더 보기좋고 더 효율적이고 더 임팩트있는 코드를 짜고싶다! div centereing 하기와 겹치는 요소도 있지만, 다시 정리해보는 vertical center
top, bottom에 여유공간을 주어 수직으로 가운데 정렬할 수 있다.
.center {
padding: 70px 0;
border: 3px solid green;
}
수직, 수평 같이 정렬을 바꾸고 싶다면, text-align만 추가해주면 된다.
padding으로 높이를 맞춰주는 방법이 가장 쉽겠지만, 박스 안에 내용이 계속해서 변할 경우에는 padding으로 정렬을 맞추기가 힘들기에 권장하지 않는 방식
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;
}
패딩이나 inline-height이 옵션이 아니라면, 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%);
}
이 모든것을 해결할 것이 나왔으니 그것은 flexbox
정렬 대상의 부모 요소에 룰셋을 선언한다.
.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}