绝对定位居中

来源:互联网 发布:nosql数据库的优点 编辑:程序博客网 时间:2024/05/01 20:34

‘’绝对定位中如何让元素进行水平垂直居中。下面是三种方法,其中方法一、方法二原理差不多[绝对定位 然后margin值取元素宽高一半(负值)],方法三就是让绝对定位上下左右都是0 然后给它一个margin: auto;
1、 方法一
主流写法。需要提前知道元素的尺寸。否则margin负值无法精确。[可通过js获取高度。]

.wrap {    width: 500px;    height: 400px;    background: #000;    position: relative;}.uP {    width: 100px;    height: 100px;    background: #ff0000;    position: absolute; /* 绝对定位 */    top: 50%;    left: 50%;    margin-top: -50px; /* 高度的一半 */    margin-left: -50px; /* 宽度的一半 */}<div class="wrap">    <div class="uP"></div></div> 

2、方法二
无论绝对定位元素的尺寸是多少,都可水平垂直居中显示 可利用CSS3中transform代替margin. transform中translate偏移的百分比值是相对于自身大小的。

.wrap {        width: 500px;        height: 400px;        background: #000;        position: relative;    }.uP {    width: 300px;    height: 300px;    background: #ff0000;    position: absolute; /* 绝对定位 */    top: 50%;    left: 50%;    transform: translate(-50%,-50%);  /* 50%为自身尺寸的一半 */} <div class="wrap">    <div class="uP"></div></div> 

PS:兼容性不好。记得写浏览器前缀transform

3、 方法三

//代码和上面一样,只是改动了.uP的样式。这个方法不管你更改外层或是外层div的宽度高度他都会自动居中。.wrap {    width: 500px;    height: 400px;    background: #000;    position: relative;}.uP {    width: 100px;    height: 100px;    background: #ff0000;    position: absolute; /*绝对定位 上下左右0*/    top: 0px;    bottom: 0px;    left: 0px;     right: 0px;    margin: auto; /*居中关键*/}<div class="wrap">    <div class="uP"></div></div>
0 0
原创粉丝点击