- 本文围绕此html书写样式
<div class="father">
<div class="child"></div>
</div>
- 实现效果图
1.使用flex布局,设置主轴,副轴居中
- 子元素必须设置宽高,不然设置flex之后子元素不会出现;
<style>
.father{
height:300px;
width:300px;
background-color: #00aeec;
display:flex;
justify-content:center;
align-items:center;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
}
</style>
</head
效果图:
2.绝对定位position:absolute+负margin
- 子元素必须给定宽高
- 父元素必须能被子元素的absolute所相对
- 子元素的absoluter上左属性为父元素的一半
- margin的属性值为子元素的一半
.father{
height:300px;
width:300px;
background-color: #00aeec;
position: relative;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
}
3.绝对定位position:absolute + transform:translate(-50%,-50%)
.father{
height:300px;
width:300px;
background-color: #00aeec;
position: relative;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
position: absolute;
top: 50%;
left: 50%;
/* 这里的50%指的是子元素的宽高的50% */
transform: translate(-50%,-50%);
}
4.margin:50% + transform:translate(-50%,-50%)
.father{
height:300px;
width:300px;
background-color: #00aeec;
/*解决外部边框坍塌 */
overflow: hidden;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
margin-top:50%;
margin-left: 50%;
transform: translate(-50%,-50%);
}
5. 绝对定位position:absolute,设置4个方向都为0, + margin:auto
- 子元素必须给宽高,否则是填满整个父元素
.father{
height:300px;
width:300px;
background-color: #00aeec;
position: relative;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
position: absolute;
top: 0;
bottom:0;
left:0;
right:0;
margin: auto;
}
6. 父元素text-align:center, +子元素在父元素中行内元素中垂直居中vertical-align:middle
- 父元素给定行高
- 子元素必须为行内元素
.father{
height:300px;
width:300px;
background-color: #00aeec;
/* 给定行高,可以垂直居中 */
line-height: 300px;
text-align: center;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
vertical-align:middle;
/* 解决文字水平居中 */
display: inline-block;
}
7.grid布局
.father{
height:300px;
width:300px;
background-color: #00aeec;
display: grid;
}
.child{
background-color: #0abf5b;
height:50px;
width:50px;
justify-self: center;
align-self: center;
}