一个好用的让DIV水平垂直居中的方法

来源:互联网 发布:mac电源适配器拆解 编辑:程序博客网 时间:2024/06/03 14:31
div{    width : 300px;    height : 300px;    border : 1px solid red;    position : absolute;    top : 50%;    left : 50%;    margin-top : -150px;    margin-left : -150px;  }

小解:
将DIV的定位设置为absolute之后,top:50%是指DIV的上边框距离外框顶部的距离是50%,但是垂直居中要保证DIV的中心距离外框顶部距离是50%,所以margin-top:-150px保证了上面的效果

也可以这样:

未知宽高:
position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);

已知宽高:
width:200px;height:200px;position:absolute;left:50%;top:50%;transform:translate(-100px,-100px);

TIPS:
负边距补充:
当 margin-top 、 margin-left 为负值的时候,会把元素上移、左移,同时文档流中的位置也发生相应变化,这点与 position:relative 的元素设置top、left后元素还占据原来位置不同
当 margin-bottom 、 margin-right 设为负值的时候,元素本身没有位置变化,后面的元素会下移、右移

0 0
原创粉丝点击