css—盒內元素水平(垂直)居中的方法


Div盒子水平垂直居中的方法

1、外邊距負值法

div{
   position: absolute;  /*絕對定位:相對於最近的且不是static定位的父元素來定位*/;
   height: 100px;
   width: 100px;     /*寬高固定*/;
   top:50%;
   left:50%;
   margin-top: -50px    /*(負高度的一半)*/;
   margin-left: -50px   /*(負寬度的一半)*/;
}

 

2、transform:translate(-50%,-50%)

div{
  width: 100px;
  height: 100px;
  position:absolute; 
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);  /*transform:translate(x,y) 定義2D 轉換*/
}

 

3、margin: auto

div{
  width: 100px;
  height: 100px;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  margin:auto;
}

如果僅僅是要求水平居中的話,可以只采用margin:0 auto。

 

4、display:flex

div{
  display:flex;
  align-items:center;
  justify-content:center;
}

Flex布局使得容器內的子元素進行排列,align-item:垂直排列方式,justify-content:水平排列方式

 


免責聲明!

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



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