CSS 3種div置中方法

參考:
How to Center a Div Using CSS Flexbox:
link: https://www.youtube.com/watch?v=4ZniRUFy824
it 幫幫忙:
link: https://ithelp.ithome.com.tw/m/articles/10303304

最終呈現結果(3 個方法最後結果都一樣):

3 Tips How to Center a Div Using CSS

首先建立 html div

<body>
  <div class="container">
    <div class="sample-div">
      <p>Im a Box</p>
    </div>
  </div>
</body>

可以先去除瀏覽器本身的內外距

<style>
  body {
    margin: 0;
    padding: 0;
    background-color: darkcyan;
  }
</style>

Tips 1 CSS Flexbox (建議用):

justify-content : 水平對齊
align-items : 垂直對齊

<style>
  /* 置中必要需求需要有 寬&高 */
  p {
    font-size: 25px; /* 小提醒:文字太大 也會佔用外面的空間 */
    margin: 0; /* p 元素本身有margin,body弄不掉所以這邊再弄 */
    text-align: center; /* 因為父元素用了display flex/grid 所以這個可以忽略 */
  }

  .container {
    display: flex; /* 顯示為 flex */
    justify-content: center; /* 水平置中 */
    align-items: center; /* 垂直置中 */
    width: 70%; /* 寬 */
    height: 400px; /* 高 */
    background-color: #000;
  }

  .sample-div {
    display: flex; /* 顯示為 flex */
    justify-content: center; /* 水平置中 */
    align-items: center; /* 垂直置中 */
    width: 200px;
    height: 200px;
    background-color: #fff;
  }
</style>

Tips 2 CSS Grid:

<style>
  /* 置中必要需求需要有 寬&高 */
  p {
    font-size: 25px; /* 小提醒:文字太大 也會佔用外面的空間 */
    margin: 0; /* p 元素本身有margin,body弄不掉所以這邊再弄 */
    text-align: center; /* 因為父元素用了display flex/grid 所以這個可以忽略 */
  }

  .container {
    display: grid; /* 顯示為 flex */
    place-items: center; /* 置中 */
    width: 70%; /* 寬 */
    height: 400px; /* 高 */
    background-color: #000;
  }

  .sample-div {
    display: grid; /* 顯示為 flex */
    place-items: center; /* 置中 */
    width: 200px;
    height: 200px;
    background-color: #fff;
  }
</style>

Tips 3 CSS margin-auto (對自己設定):

margin 沒有垂直效果需要搭配 position 來產生效果

<style>
  p {
    font-size: 25px; /* 小提醒:文字太大 也會佔用外面的空間 */
    margin: 0; /* p 元素本身有margin,body弄不掉所以這邊再弄 */
    text-align: center; /* 因為父元素用了display flex/grid 所以這個可以忽略 */
  }

  .container {
    width: 70%; /* 寬 */
    height: 400px; /* 高 */
    background-color: #000;
    position: relative;
  }

  .sample-div {
    position: absolute; /* 絕對定位 */
    margin: auto; /* 置中 */
    /* margin沒有垂直置中效果,需要搭配 position來產生效果 */
    top: 0; /* 上 */
    bottom: 0; /* 下 */
    left: 0; /* 左 */
    right: 0; /* 右 */
    display: flex; /* 這邊是為了讓文字置中 */
    justify-content: center; /* 這邊是為了讓文字置中 */
    align-items: center; /* 這邊是為了讓文字置中 */
    width: 200px;
    height: 200px;
    background-color: #fff;
  }
</style>

Tips 4 CSS :

<style>
  .center {
    height: 200px;
    position: relative;
    border: 3px solid green;
  }

  .center p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 kimfei2014@gmail.com
github