CSS-水平垂直居中
文章目录
这是笔者近日面试中遇到的一个“棘手”问题,所谓棘手,是因为CSS这个东西不经常写的话,是一定会忘,会手生的。笔者只是提及了最常见也是最简单的Flex,却被面试官继续追问,本以为会根据记忆写出来点什么,最后却无奈。。。
话不多说了,上干货。
CSS垂直居中的方式,这里我都以父元素嵌套子元素的形式展开:
已知子元素的宽高的情况下:
absolute + margin:auto
.parent{
width:500px;
height:500px;
border:1px solid #ccc;
position:relative;
}
.children{
width:300px;
height:300px;
background-color:red;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}absolute + -margin:
.parent{
/*同上面的盒子那样*/
}
.children{
width:300px;
height:300px;
background-color:red;
position:absolute;
top:50%;
left:50%;
margin-top:-150px;
margin-left:-150px;
}子元素宽高未知的情况下:
flex布局:
.parent{
display:flex;
justify-content:center;
align-item:center;
}absolute + transform:
.parent{
position:relative;
/*宽高同上面的盒子一样,这里不再重复设置了*/
}
.children{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论