水平居中
1.子父元素宽度固定,子元素设置 margin:auto,并且子元素不能设置 浮动,否则居中失效
2.子父元素宽度固定,父元素设置 text-align:center,子元素设置 display:inline-block,并且子元素不能设置浮动,否则居中失效
<div class="father">
<div class="son">
</div>
</div>
.father{
width: 100px;
height: 100px;
border: 1px solid red;
text-align: center;
}
.son{
width: 50px;
height: 50px;
border: 1px solid blue;
display: inline-block;
/* margin: auto; */
}
水平垂直居中
子元素相对于父元素绝对定位,子元素 top,left 设置 50%,子元素 margin-top 和 margin-left 减去各自宽高的一半
<div class="father">
<div class="son">
</div>
</div>
.father{
width: 100px;
height: 100px;
border: 1px solid red;
position: relative;
}
.son{
width: 50px;
height: 50px;
border: 1px solid blue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
}
子元素相对于父元素绝对定位,子元素上下左右全为 0,然后设置子元素 margin:auto
.father{
width: 100px;
height: 100px;
border: 1px solid red;
position: relative;
}
.son{
width: 50px;
height: 50px;
border: 1px solid blue;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
子元素相对定位,子元素 top,left 值为 50%,transform:translate (-50%,-50%)
或者 子元素相对父元素绝对定位,子元素 top,left 值为 50%,transform: translate(-50%,-50%)
.father{
width: 100px;
height: 100px;
border: 1px solid red;
}
.son{
width: 50px;
height: 50px;
border: 1px solid blue;
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
父元素设置弹性盒子, display:flex; justfy-content:center ;align-item:center;
.father{
width: 100px;
height: 100px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 50px;
height: 50px;
border: 1px solid blue;
}