在未知宽高度的情况设置子元素垂直水平居中
效果图:
html代码:
<div class="parent">
<div class="child">我是子元素</div>
</div>
解决方案
在子元素未知宽高度的情况下:
使用flex布局
.parent{
width:300px;
height: 300px;
background: red;
display: flex;
justify-content: center; //水平居中
align-items: center; //垂直居中
}
.child{
background: blue;
}
使用transform
.parent{
position:relative;
width:300px;
height: 300px;
background: red;
margin: auto;
}
.child{
background: blue;
position: absolute;
top:50%;
left:50%; //这里设置top和left的值,使元素的左上角的坐标位于中心
transform: translate(-50%,-50%); //translate是以左上角为中心移动,所以只需往
上和往左个移动子元素的一半即可
}
父元素设置为table-cell
.parent{
width:300px;
height: 300px;
background: red;
display: table-cell;
vertical-align: middle; //使元素在垂直上居中
text-align: center; //使元素在水平上居中
}
.child{
background: blue;
display: inline-block;
}
在子元素知道宽高度下:
使用绝对定位
先设置为绝对定位,然后使用top和left将左上角移至中心点,然后使用margin进行移动,其中移动的距离为元素的一半
.parent{
position:relative;
width:300px;
height: 300px;
background: red;
margin: auto;
}
.child{
position: absolute;
width:200px;
height: 200px;
background: blue;
top:50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
绝对定位和相对定位相配合
这个思想比较强硬,设置父元素为的定位为相对定位,然后子元素设置为绝对定位,使得子元素根据父元素进行定位,再利用margin属性进行移位(移的距离根据子元素的宽高度来设定)
.parent{
position:relative;
width:300px;
height: 300px;
background: red;
margin: auto;
}
.child{
position: absolute;
width:200px;
height: 200px;
background: blue;
margin-top:50px;
margin-left: 50px;
}