用到的HTML代码如下:
<div class="parent">
<div class="child"></div>
</div>
一、vertical-align实现水平垂直居中(child无须固定宽高)
vertical-align只对inline-block型起作用,即display为 inline-block 和 table-cell的
1、 display:inline-block
.parent {
width: 300px;
line-height: 300px;
border: 1px solid #b766dd;
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
width: 4px;
height: 4px;
background: rgb(4, 57, 170);
}
2、display:table-cell
.parent {
width: 300px;
height: 300px;
border: 1px solid #b766dd;
display: table-cell;
vertical-align: middle;
}
.child {
width: 4px;
height: 4px;
background: rgb(4, 57, 170);
margin: 0 auto;
}
3、:after伪类
.parent {
width: 300px;
height: 300px;
border: 1px solid #b766dd;
text-align: center;
}
.child {
width: 4px;
height: 4px;
background: rgb(4, 57, 170);
display: inline-block;
}
.parent:after{
content:"";
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
}
二、position定位
1、child固定宽高
.parent {
width: 300px;
height: 300px;
border: 1px solid #b766dd;
position: relative;
}
.child {
width: 4px;
height: 4px;
background: rgb(4, 57, 170);
position: absolute;
top: 50%;
left: 50%;
margin-top: -2px;
margin-left: -2px;
}
2、child不固定宽高
.parent {
width: 300px;
height: 300px;
border: 1px solid #b766dd;
position: relative;
}
.child {
width: 4px;
height: 4px;
background: rgb(4, 57, 170);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
三、flex
.parent {
width: 300px;
height: 300px;
border: 1px solid #b766dd;
display: flex;
justify-content: center;/*水平*/
align-items: center;/*垂直*/
}
.child {
width: 4px;
height: 4px;
background: rgb(4, 57, 170);
}
网友评论