본문 바로가기
Programming/Javascript

absolute와 flex로 블록 중간에 두기

by peter paak 2019. 11. 20.
728x90

position:absolute와 display:flex로 블록을 화면 중간에 둘 수 있다.

<div className="test">
    <div>Block</div>
    <div>Login</div>
</div>
.test {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;

    display: flex;
    justify-content: center;
    align-items: center;
}
  • 배경색은 html, body, *, 각 블록 별로 자유롭게 설정

차레대로 살펴보자

position : absolute

absolute 포지션을 사용하게 되면 기준은 화면의 제일 왼쪽 상단 (0,0)에서 시작한다.

position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;

top, bottom, left, right의 속성을 모두 0으로 맞추면 absolute된 블락은 화면의 상하좌우의 끝으로 늘어나게 된다.

position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;

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

그 상태에서 display:flex 옵션을 주게되면 absolute가 적용된 블록은 화면 전체에 늘어나 있는 상황이기 때문에 내부의 자식들은 화면 전체를 대상으로 정렬이 가능하다. justify-content와 align-item을 center로 적용하면 화면전체를 대상으로 수직, 수평으로 center에 놓을 수 있다.

만약, posotion이 absolute가 아닌 경우, 즉 static이나 relative와 같은 normal flow를 따르는 속성들을 높이가 각 블록들의 높이에 따라 영향을 받는다. 전체 높이는 position이 결정하는 것이 아니라 그 하위 자식 블록들의 높이에 따라 달라진다. 따라서 전체 높이를 조절해야되는 경우 absolute와 flex의 조합을 사용하는 것이 좋다.

728x90