摘自https://www.cnblogs.com/Julia-Yuan/p/6648816.html
水平垂直居中
一.對於肯定寬度的塊級元素:
脫離文檔流元素的居中
方案一:
div絕對定位水平垂直居中【margin:auto實現絕對定位元素的居中】,html
div{ width: 200px; height: 200px; background: green; position:absolute; left:0; top: 0; bottom: 0; right: 0; margin: auto; }
方案二:
div絕對定位水平垂直居中【margin 負間距】web
div{ width:200px; height: 200px; background:green; position: absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px; }
方案三:瀏覽器
div絕對定位水平垂直居中【Transforms 變形】
兼容性:IE8不支持;svg
div{ width: 200px; height: 200px; background: green; position:absolute; left:50%; /* 定位父級的50% */ top:50%; transform: translate(-50%,-50%); /*本身的50% */ }
2、對於未知寬度的塊級元素:
1.彈性盒子flex
.box{ height:600px; display:flex; justify-content:center; align-items:center; /* aa只要三句話就能夠實現不定寬高水平垂直居中。 */ } .box>div{ background: green; width: 200px; height: 200px; }
2.將父盒子設置爲table-cell元素,可使用text-align:center和vertical-align:middle實現水平、垂直居中。code
/* table-cell實現居中 將父盒子設置爲table-cell元素,設置 text-align:center,vertical-align: middle; 子盒子設置爲inline-block元素 .cell { display: table-cell; vertical-align: middle; text-align: center; width: 240px; height: 180px; border:1px solid #666; } .cell #aa{ display:inline-block; height: 30px; width: 30px; background-color: red; } </style> </head> <body> <div class="cell"> <p>我愛你</p> </div> <div class="cell"> <p>我愛你</p><p>親愛的中國</p> </div> <div class="cell"> <p>我愛你</p><p>親愛的中國</p><div style="width:100px;height:50px;border:1px solid #ccc;display:inline-block">div(inline-block)</div> </div> <div class="cell"> <p id="aa"></p> </div>
實現水平居中orm
(1)table標籤配合margin左右auto實現水平居中xml
使用table標籤(或直接將塊級元素設值爲display:table),再經過給該標籤添加左右margin爲autohtm
(2)inline-block實現水平居中方法blog
display:inline-block;(或display:inline)和text-align:center;實現水平居中 存在問題:需額外處理inline-block的瀏覽器兼容性(解決inline-block元素的空白間距)
(3)絕對定位實現水平居中
絕對定位+transform,translateX能夠移動本省元素的50% .content{ position: absolute; left: 50%; transform: translateX(-50%); /* 移動元素自己50% */ background: aqua; }
不懂(4)相對定位實現水平居中
用float或者display把父元素變成行內塊狀元素
.contentParent{
display: inline-block; /* 把父元素轉化爲行內塊狀元素 */
/*float: left; 把父元素轉化爲行內塊狀元素 */
position: relative;
left: 50%;
}
/目標元素/
.content{
position: relative;
right: 50%;
background-color:aqua;
}
(5)CSS3的flex實現水平居中方法,法一
.contentParent{
display: flex;
flex-direction: column;
}
.content{
align-self:center;
}
(6)CSS3的flex實現水平居中方法,法二
.contentParent{
display: flex;
}
.content{
margin: auto;
}
(7)CSS3的fit-content配合左右margin爲auto實現水平居中方法
.content{
width: fit-content;
margin-left: auto;
margin-right: auto;
}
實現垂直居中