一、块元素中的文字、行内元素、inline-block元素:
1. 左右居中: text-align: center; 或者给子元素加 margin: 0 auto;
2. 上下居中: line-height: 100px; (这里的line-height等于该块元素的height)
<div style="width:100px; height:100px; text-align:center; line-height:100px;">
123
</div>
二、块元素中的块元素:
1. 计算子元素的块margin-top为(父高度 - 子高度)/2 margin:25px auto;
<div class="parent" style="width: 100px; height: 100px; border: 1px solid #ccc;">
<div class="children" style="width: 50px; height: 50px; border: 1px solid #ccc; margin: 25px auto;">
</div>
</div>
2. 父元素相对定位,子元素绝对定位
.parent {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.children {
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
width: 50px;
height: 50px;
border: 1px solid #ccc;
}
2. 或者: 父元素样式不变,子元素样式改为
.children {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 50px;
height: 50px;
border: 1px solid #ccc;
}
3. flex布局:
.parent {
display: flex;
width: 100px;
height: 100px;
align-items: center;
justify-content: center;
border: 1px solid #ccc;
}
.children {
width: 50px;
height: 50px;
border: 1px solid #ccc;
}