CSS Centering 5가지 방법

nona·2021년 1월 31일
0

CSS

목록 보기
2/2

가장 많이 쓰는 방법:
centering하고싶은 아이템들을 div로 하나로 묶은다음에
그 div에 display: flex, align-items: center (수직정렬) 주거나
display: flex, justify-contents: center (수평정렬)

1. block item의 경우

: div, h1-h6, p, form, header, footer, section같은 block item의 경우, 혹은 display: block을 따로 주는 경우

display: block;
width: 50%;
margin: 0 auto;

margin 의 오른쪽 왼쪽을 auto로 주어서 centering을 할수있다.
한가지 주의할 점은 이경우에는 꼭! width를 함께주어야 한다는 것.
수직으로도 centering을 하고 싶으면 text-align: center;
을 넣어주면 된다.

2. flexbox의 경우

display: flex;
align-items: center;
justify-content: center;

justify-content는 수평정렬
align-items는 수직정렬

3. 박스 안에 있는 박스의 경우

top: 50%;
left: 50%;
transform: translate(-50%, -50%);

박스의 경우에는 왼쪽 상단 모서리 끝을 기준으로 박스가 움직이기때문에 50%씩 이동한 후에, transform으로 -50% 씩 빼주어서 정 가운데로 맞추는 것.

4. div 안에 있는 텍스트의 경우

text-align: center;
line-height: 100px //부모 상자의 크기만큼 주면 됨. 이경우에는 <br/>못씀

text-align은 수평정렬
lien-height는 수직정렬

5. block이 아닌 아이템들의 경우

div처럼 block이 아닌 button같은 아이템의 경우에는 기본 margin이 없기 때문에

text-align: center;

요거 하나로도 center가 된다.

0개의 댓글