1.利用定位法(子绝父相)
width: 300px;
height: 300px;
background: pink;
position: relative;
}
.son {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top:50%;
left:50%;
margin-top: -50px;
margin-left: -50px;
}
2.margin: auto;
width: 300px;
height: 300px;
background: pink;
position: relative;
}
.son {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
3.transform
width: 300px;
height: 300px;
background: pink;
position: relative;
}
.son {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50px, -50px);
}
4.flex
width: 300px;
height: 300px;
background: pink;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 100px;
height: 100px;
background: greenyellow;
}
- display: table-cell;
width: 300px;
height: 300px;
background: pink;
/* display: table-cell; 意思是将元素设置为表格单元格。
这意味着该元素将作为表格中的一个单元格呈现,并且可以与其他单元格并列。 */
display: table-cell;
/* 设置元素的垂直对齐方式。它可以将元素相对于父元素的中心线垂直居中对齐。 */
vertical-align: middle;
text-align: center;
}
.son {
width: 100px;
height: 100px;
background: greenyellow;
/* 把子盒子转成行内元素 */
display: inline-block;
}