새소식

인기 검색어

개인공부/HTML5&CSS3

position으로 가운데정렬하기

  • -

css 가운데 정렬

📌 일반적인 가운데 정렬 방법

1. 부모요소가 block이고 자식 요소가 inline 일 때

.부모{
    text-align: center;
}

2. block 일 때

.요소{
    margin: 0 auto;
    width: 100px; /* width값 필요함 */
}

 

📌 position: absolute 로 지정 되어있을 때

📝 html

<div class="parent">
    <div class="child">
    </div>
</div>

📝 css

.parent{
    width: 100%;
    position: relative;
}
.child{
    width: 100px;
    position: absolute;
}

1. top: 50% left: 50%

.child{
    width: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
}

여기까지 해주면 자식요소가 정 가운데에 위치하게 되는데 다음과 같이 요소의 맨 왼쪽, 맨 위쪽 좌표를 기준으로 가운데로 가게 되어버린다.

위를 완전히 가운데로 오게 하기위해서는 다음과 같이 translate를 사용하거나 margin-left 를 이용하면 해결할 수 있다.


2-1. translate 이용

.child{
    width: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

📢 이렇게 간단하게 가운데로 오게 할 수 있지만 can i use 사이트에서 확인하여 크로스 브라우징을 염두하여 사용해야한다.

2-2. margin 이용

.child{
    width: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* width의 50% */
    margin-top: -50px; /* height의 50% */
}

✌ 결과

'개인공부 > HTML5&CSS3' 카테고리의 다른 글

[CSS] transition, transform, translate 정리  (0) 2022.09.22
PROJECT  (0) 2022.09.22
CSS 애니메이션(@keyframes 와 animation 속성)  (0) 2022.09.16
프로젝트 하면서 알아낸것  (0) 2022.09.15
(HTML) 데이터 속성  (0) 2022.09.13
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.