例如有一个父子div如下:
<div class="parent">
<div class="child"></div>
</div>
如何实现图示效果呢:
首先初始化一下css便于展示效果:
.parent {
width: 500px;
height: 500px;
background: #ffd700;
}
.child {
width: 100px;
height: 100px;
background: #9400d3;
}
方法1:相对定位和绝对定位的搭配使用(常用方法)
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
将父盒子设置为相对定位,子盒子设置为绝对定位,进行定位,需要注意的是定位中心是子盒子的左上顶点,所以需要减去盒子的一半的像素,即回退一半的距离。
方法2:flex布局(父元素指定子元素居中)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
直接将父盒子设置为flex布局方式,然后利用flex最为常用的两个属性justify-content:center与align-items:center变可以实现其子盒子水平垂直居中。
方法3:极简实现,最佳方案,只需要考虑flex!
.parent {
display: flex;
}
.child {
margin: auto;
}
方法3是方法2的另一种实现,都是利用flex布局技巧,子盒子的margin属性设为auto变可以自动实现居中效果。
附加问一:如何水平居中一个元素?
答:
①如果需要居中的元素为 inline 或 inline-block,为父元素设置 text-align: center;
②如果要居中的元素为一个块级元素,使用 margin: auto; 进行水平居中。
③ 如果元素positon: absolute; 那么 (0)设置父元素postion: relative(1)为元素设置宽度,(2)偏移量设置为50%,(3)偏移方向外边距设置为元素宽度一半乘以-1
.parent{
position: relative;
}
.center {
width: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
}
④ 如果元素positon: relative; 那么 (1)为元素设置宽度(2)偏移量设置为50%(3)偏移方向外边距设置为元素宽度一半乘以-1
.child{
width: 100px;
position: relative;
left: 50%;
margin-left: -50px;
}
附加问二:如何垂直居中一个元素?
①元素固定宽高
- 绝对定位,top为 50%, margin-top 为负的自身高度一半
.center {
width: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
}
- 绝对定位,calc计算函数, top 为父元素一半减自身一半
.center {
width: 100px;
position: absolute;
top: calc(50% - 50px);
}
②元素不需要固定宽高
- 绝对定位,top为50%,translate设置(0,-50%)
.center {
position: absolute;
top: 50%;
transform: translate(0,-50%);
}
- 父元素设置flex布局,子元素设置 margin: auto 0;
.parent{
display: flex;
}
.child{
margin: auto 0;
}