본문 바로가기
CSS

[CSS] 화면에 요소 정가운데에 위치시키는 방법 (반응형!!!) + 텍스트 가운데 배치

by img 2021. 10. 19.

어떻게 하면 부모요소 정 가운데에 반응형으로 위치시킬 수 있을까? 

1. flex 사용하는 방법 (개인적으론 flex방법을 선호한다ㅎㅎㅎ)

부모요소에 display:flex; justify-content:center; align-items:center;

<html>
  <body>
    <div class="container">
      <div class="item">item</div>
    </div>
  </body>
</html>
<style>
  .container{
    width:100%;
    height:100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .item{
    width:50px;
    height:50px;
    background-color:beige;
  }
</style>

2. absolute & translate 사용하는 방법

자식요소에 position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);

<html>
  <body>
    <div class="container">
      <div class="item">item</div>
    </div>
  </body>
</html>
<style>
  .container{
  }
  .item{
    width:50px;
    height:50px;
    background-color:beige;
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
  }
</style>

 

++ 추가

박스 안에 글자까지 가운데에 위치시키고 싶다면

자식요소에 display:flex; justify-content:center; align-items:center; 를 추가해주면 된다.

<html>
  <body>
    <div class="container">
      <div class="item">item</div>
    </div>
  </body>
</html>
<style>
  .container{
    width:100%;
    height:100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .item{
    width:50px;
    height:50px;
    background-color:beige;
    
    display:flex;
    justify-content:center;
    align-items:center;
  }
</style>

이렇게 하면

짜잔

 

 

댓글