水平居中
一、如果是行內(nèi)元素,則設(shè)置
text-align: center;
二斜做、如果是塊級(jí)元素或者行內(nèi)塊級(jí)元素
則有以下幾種:
- 子元素設(shè)置margin: 0 auto;
margin: 0 auto;
- 父元素設(shè)置flex 和 justify-content
display: flex;
justify-content: center;
- 父元素相對(duì)定位兑凿,子元素絕對(duì)定位
/* 父元素 */
position: relative;
/* 子元素 */
position: absolute;
left: 50%;
transform: translateX(-50%);
/* 或者 */
margin-left: -50%;
/* 或者 */
left: 0;
rigth: 0;
margin: 0 auto;
- 盒模型
/* 父元素 */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
垂直居中
一、 如果是單行文本則設(shè)置light-height等于元素的高度
二盼产、如果是行內(nèi)塊級(jí)元素或者塊級(jí)元素
- flex布局
display: flex;
align-items: center;
- 定位
/* 父元素相對(duì)定位 */
position: relative;
/* 子元素 */
position: absolute;
top: 50%;
margin-top: -50%;
/* 或 */
transform: translateY(-50%);
/* 或 */
top:0;
bottom:0;
margin:auto 0;
- 盒模型
display: -webkit-box;
-webkit-box-orient:vertical;
-webkit-box-pack: center;
- calc 動(dòng)態(tài)計(jì)算
父元素隨意
/*子元素*/
width: 100px;
height:100px;
position: relative;
/* 距離頂部的百分比 - 子元素自身高度的一半*/
top: calc(50% - 50px);
margin: auto;
- 元素高度不固定時(shí)
/* 父元素 */
display: table;
/* 子元素 */
dispaly: table-cell
vertical-align: center;