CSS水平垂直居中之fit-content布局


實現一個元素水平垂直居中的方法很多:

  • 元素未知寬高

width和height的fit-content值只支持Chrome和Firefox瀏覽器

 1 .box {
 2     position: absolute;
 3     top: 0;
 4     left: 0;
 5     bottom: 0;
 6     right: 0;
 7     margin: auto;
 8     width: fit-content;
 9     width: -webkit-fit-content;
10     width: -moz-fit-content;
11     height: fit-content;
12     height: -webkit-fit-content;
13     height: -moz-fit-content;
14     overflow: hidden;
15     text-align: center;
16     background-color: #eee;
17 }
  • 元素已知寬高

大家對這個應該是很了解的,也是實際開發中運用最多的,推薦給剛剛入門的小伙伴吧。

設置它的父元素為position:relative即可:

第一種方式:

 1 .children{
 2     position: absolute;
 3     top: 0;
 4     bottom: 0;
 5     left: 0;
 6     right: 0;
 7     margin: auto;
 8     width: 300px;
 9     height: 200px;
10     background-color: #5f9a3f;
11 }

第二種方式:

1 .children{
2     position: absolute;
3     top: 50%;
4     left: 50%;
5     margin: -100px 0 0 -150px;
6     width: 300px;
7     height: 200px;
8     background-color: #5f9a3f;
9 }

第三種方式:

使用CSS3新屬性transform的translate屬性

1 .children{
2     position: absolute;
3     top: 50%;
4     left: 50%;
5     transform: translate(-50%,-50%);
6     width: 300px;
7     height: 200px;
8     background-color: #5f9a3f;
9 }

感謝閱讀,歡迎大家來吐糟。

 


免責聲明!

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



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