實現元素水平垂直居中的四種方法


讓元素水平垂直居中的四種方法

前言

一、使用 transform 與 position 結合

二、使用 position 定位和 偏移 屬性

三、使用 position 定位和 外邊距 屬性

四、使用 flex 彈性布局

方法一

主要利用transform屬性實現上下左右居中

CSS部分

.demo {
      width: 100px;
      height: 100px;
      background-color: greenyellow;
      /* 定位須是絕對定位 */
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
}

html部分

<div class="demo"></div>

頁面效果展示

方法二 (常用方法)

主要利用absolute屬性和偏移屬性實現上下左右居中

CSS部分

.demo {
      width: 100px;
      height: 100px;
      background-color: yellowgreen;
      /* 定位須是絕對定位 */
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      margin: auto;
}

html部分

<div class="demo"></div>

方法三

主要利用absolute屬性和外邊距屬性實現上下左右居中

CSS部分

.demo {
      width: 100px;
      height: 100px;
      background-color: yellow;
      /* 定位須是絕對定位 */
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -50px;
}

html部分

<div class="demo"></div>

方法四

主要利用flex彈性布局

注意

1、首先將父元素設置為 display:flex;justify-content: center;align-items: center;

2、其次將父元素高度設置為 height:100vh,根據 css3 的規范,1vh 等於視口高度的1%(1vw 等於視口寬度的1%),那么 100vh 就是適口高度的 100%,即占滿整個屏幕。

CSS部分

html,body  {
      margin: 0;
}
.container {
      height: 100vh;
      /*設置外層盒子display為flex*/
      display: flex;
      /*設置內層盒子水平居中*/
      justify-content: center;
      /*設置內層盒子垂直居中*/
      align-items: center;
      margin: 0 auto;
}
.demo  {
      width: 100px;
      height: 100px;
      background-color: green;
}

html部分

<div class="container">
      <div class="demo"></div>
</div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM