让某个元素在水平和垂直的方向都居中 内容不限于文字,可能会是图片和其他元素
方法一:定位 + margin负值
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: aquamarine;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px; /* 子盒子宽度的一半 */
margin-top: -100px; /* 子盒子高度的一半 */
}
</style>
<div class="father">
<div class="son"></div>
</div>
方法二:定位 + transform负值
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: aquamarine;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="father">
<div class="son"></div>
</div>
方法三:定位 + margin: auto
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: aquamarine;
position: absolute;
/* 以下四个属性必须都要写上 */
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<div class="father">
<div class="son"></div>
</div>
方法四:flex布局
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
display: flex;
justify-content: center; /* 主轴居中 */
align-items: center; /* 侧轴居中 */
}
.son {
width: 200px;
height: 200px;
background-color: aquamarine;
}
</style>
<div class="father">
<div class="son"></div>
</div>
方法五:table布局
将父元素设置 display:table-cell 子元素设置 display: inline-block
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.son {
width: 200px;
height: 200px;
background-color: aquamarine;
display: inline-block;
}
</style>
<div class="father">
<div class="son"></div>
</div>
方法六:grid网格布局
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
display: grid;
align-items: center;
justify-content: center;
}
.son {
width: 200px;
height: 200px;
background-color: aquamarine;
}
</style>
<div class="father">
<div class="son"></div>
</div>
小结
上述方法不知道元素大小 但仍然可以实现水平垂直居中的有
- 定位 + transform负值
- 定位 + margin: auto
- flex布局
- table布局
- grid网格布局
行内元素的居中布局
水平居中
- text-align: center
- 父元素 display: flex justify-content: center
垂直居中
- 单行文本:height = line-height
- 多行文本:disaply: table-cell; vertical-align: middle
块级元素居中布局
水平居中
- margin: 0 auto
- 定位 + left: 50% + transform: translateX(-50%);
- 定位 + left: 50% + margin-left: 负的自己宽度一半;
垂直居中
- 定位 + top: 50% + transform: translateY(-50%);
- 定位 + top: 50% + margin-top: 负的自己宽度一半
- flex布局