<body>
<div class="parent">
<div class="child">
child
</div>
</div>
</body>
複製代碼
*{
margin: 0;
padding: 0;
}
.parent{
width: 100px;
height: 100px;
/*將padding設置,來擠出來居中的樣子;可是要注意的是,此時的width和height要和子元素的大小同樣,不然仍是不居中*/
padding: 100px;
border: 1px solid;
margin: 100px auto;
}
.child{
width: 100px;
height: 100px;
background: pink;
line-height: 100px;
text-align: center;
}
複製代碼
*{margin: 0;padding: 0;}
.parent{
position: relative;
width: 200px;
height: 200px;
/*padding: 100px;*/
border: 1px solid;
margin: 100px auto;
}
.child{
position: absolute;
/*left+right+width+padding+margin=包含塊的寬度*/
/*0 0 100 0 auto =300*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background: pink;
line-height: 100px;
text-align: center;
}
複製代碼
.parent{
position: relative;
width: 200px;
height: 200px;
border: 1px solid;
}
.child{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background: pink;
line-height: 100px;
text-align: center;
}
複製代碼
transfrom:translate3d(-50% -50% );
/* width: 100px;
height: 100px; */
複製代碼
<style>
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}
</style>
複製代碼
// 父元素設置
display: flex;
justify-content:center;
align-items:Center;
複製代碼
line-height: 50px;
text-align:center;
複製代碼
display: flex;
justify-content:center;
align-items:Center;
複製代碼
單方面的水平居中或者垂直居中佈局,均可以按照上面的方法來實現bash