基于translate的水平垂直居中,适用于宽度已知,高度不固定的场景

水平垂直居中项目中会遇到的比较多,解决方案也有多种,今天刚学到一种 用translate来解决水平垂直居中的方案,说这个方案前先说一下之前我经常解决水平垂直居中的一个方案

<style>
 .box{position:fixed;top:50%;left:50%;width:100px;height:100px;margin-left:-50px;margin-top:-50%;background:red;}
</style>
<div class="box"></div>

上面的这种方案必须是在宽高都明确的情况下,才可以水平垂直居中,

而如果现在只知道宽,高不固定,需要根据元素内部内容的多少而高度进行变化的情况下,又想水平垂直居中,那么可以使用translate来解决

<style>
.box{position:fixed;top:50%;left:50%;width:100px;transform:translate(-50%,-50%);background:green;}
</style>
<div>translate </div>

translate 移动元素的方式可以总结归纳为三种:水平移动,上下垂直移动,对角移动

水平移动 向右移动 translate(x,0); 向左移动 translate(-x,0)

上下移动 向上移动 translate(0,-y); 向下移动 translate (0,y);

对角移动 向右下角移动 translate(x,y) 向 右上角移动 translate(x,-y); 向左下角移动  translate(-x,y) 向左上角移动 translate(-x,-y)

 

posted @ 2015-04-10 10:59  sandraBlog  阅读(289)  评论(0编辑  收藏  举报