话不多说直接上代码
html代码统一如下:
<div class="wrap">
<div class="inner">
innerBox
</div>
</div>
css代码统一如下:
定位方法A position + relative + absolute
.wrap {
width: 300px;
height: 300px;
background: yellow;
/*加颜色是为了看界面效果*/
position: relative;
}
.inner {
width: 40px;
height: 40px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: orange;
/*加颜色是为了看界面效果*/
}
定位方法B position + relative + absolute + margin
.wrap {
width: 300px;
height: 300px;
background: yellow;
/*加颜色是为了看界面效果*/
position: relative;
}
.inner {
width: 40px;
height: 40px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -20px;
margin-top: -20px;
background: orange;
/*加颜色是为了看界面效果*/
}
定位方法C position + relative + absolute + transform 针对未知宽高的元素
.wrap {
width: 300px;
height: 300px;
background: yellow;
/*加颜色是为了看界面效果*/
position: relative;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: orange;
/*加颜色是为了看界面效果*/
}
弹性布局 display flex
.wrap {
width: 300px;
height: 300px;
background: yellow;
/*加颜色是为了看界面效果*/
display: flex;
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
}
.inner {
background: orange;
}
表格布局 display table cell
.wrap {
width: 300px;
height: 300px;
background: yellow;
/*加颜色是为了看界面效果*/
display: table-cell;
text-align: center;
vertical-align: middle;
}
.inner {
display: inline-block;
background: orange;
}