SeonHyungJo / Tip-Note

:round_pushpin: 개발을 하면서 느끼고 알게된 Tip:round_pushpin:
7 stars 0 forks source link

CSS로 Content를 중앙정렬하는 4가지 방법 #53

Open SeonHyungJo opened 4 years ago

SeonHyungJo commented 4 years ago

Table

<div class="container">
  <div class="center">
    <span>Table center content</span>
  </div>
</div>
* {
    box-sizing: border-box;
  }

  body {
    margin: 0px;
    padding: 0px;
  }

  .container {
    border: 10px solid #333;
    height: 100vh;
    width: 100%;
  }

  .center {
    display: table;
    height: 100%;
    width: 100%;
  }

  .center>span {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
  }

Flexbox

<div class="flexbox-centering">
  <div class="child">Centered flexbox content.</div>
</div>
* {
    box-sizing: border-box;
  }

  body {
    margin: 0px;
    padding: 0px;
  }

  .flexbox-centering {
    display: flex;
    justify-content: center;
    align-items: center;

    border: 10px solid #333;
    height: 100vh;
    width: 100%;
  }

Grid

<div class="grid-centering">
  <div class="child">Centered grid content.</div>
</div>
* {
    box-sizing: border-box;
  }

  body {
    margin: 0px;
    padding: 0px;
  }

  .grid-centering {
    display: grid;
    justify-content: center;
    align-items: center;

    border: 10px solid #333;
    height: 100vh;
    width: 100%;
  }

Transform

<div class="parent">
  <div class="child">Centered transform content</div>
</div>
* {
    box-sizing: border-box;
  }

  body {
    margin: 0px;
    padding: 0px;
  }

  .parent {
    border: 10px solid #333;
    height: 100vh;
    width: 100%;
  }

  .child {
    left: 50%;
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
  }