理解绝对定位

出现

CSS绝对定位设置为绝对定位的元素框从文档流完全删除,并相对于其包含块定位,包含块可能是文档中的另一个元素或者是初始包含块,不占据空间。

效果

  1. 脱离文档流
  2. 容器 absolute 后,容器会包裹子元素
  3. 子元素 absolute 后,容器的高度会塌陷
  4. absolute 后的子元素,不会受无定位父容器的 overflow 所影响

无依赖的绝对定位

无依赖的绝对定位

不受 relative 限制的 absolute 定位,行为表现上是不使用 top / bottom / left / right 任何一个属性或是 auto 值

特点

  1. 位置跟随性
    原来什么位置,absolute 后还是什么位置,只是漂浮起来了

应用

配合 margin 进行精确定位
优点:1. 支持负值定位 ; 2. 兼容性IE6+

例子:图标定位

原来的实现方案:

  • 容器 relative,子元素 absolute 定位

利用跟随性后:

  • 容器无定位,子元素 absolute 利用 margin 定位

有依赖的绝对定位

用法

  1. 位移
    top - left / top - right
    bottom - left / bottom - right
  2. 拉伸(IE7+)
    left - right / top - bottom

特点

  1. 与 width / height 相互替代
    很多情况下,绝对定位的拉伸和 width/height 是可以相互替代的
    width : 100% ; height : 100% ; <==> top:0; left:0; right:0; bottom:0;
    left:0; top:0 width:50%; <==> left:0; top:0; right:50%;

  2. 与 width / height 相互支持
    容器无需 width / height 值,内部元素亦可以拉伸;
    容器拉伸(宽高不固定),内部元素支持百分比 width / height 值;

  3. 相互合作性(IE8+)
    当尺寸限制、拉伸 与 margin:auto 同时出现时,就能实现绝对居中效果

例子:遮罩

.container{
     /*容器不固定宽高*/
     display : inline-block;
     position : absolute;  
}

.cover{
     position : absolute;
     /*容器拉伸*/
     left:0;top:0;right:0;bottom:0;
     background-color:#fff;
     opacity: .5; filter:alpha(opacity=50);
}

例子:左右半区翻图浏览效果

.prev,.next{
    /*覆盖容器的一半*/
    width:50%;
    /*上下拉伸*/
    position:absolute;top:0;bottom:0;
    background-image: ;
    outline:none;
}

.prev{cursor:url(),auto; left:0 }
.next{cursor:url(),auto; right:0}

例子:高度自适应的九宫格

.page{
    position:absolute;
    left:0;top:0;right:0;bottom:0;
}

.list{
   float:left;
   height:33.3%;width:33.3%;
   position: relative;
}

例子:垂直水平居中


.container{
     position:absolute
     top:0;right:0;left:0;bottom:0;
     margin:atuo;
}

例子:网页整体布局

优点:适合移动端
头部尾部以及侧边栏都是fixed效果,不跟随滚动
可以防止移动端使用position:fixed带来的问题

<!-- 遮罩与page平级 -->
<div class="page"></div>
<div class="overlay"></div>
html,body{height:100%}
.page{position:absolute;left、top、right、bottom:0;}

/*顶部、底部*/
header,footer{position;left、right:0}
header{height:48px;top:0}
footer{height:52px;bottom:0}

/*侧边栏*/
.aside{width:250px;position:absolute;left:0;top:0;bottom:0;

/*内容区*/
.content{position:absolute;top:48px;bottom:52px;left:250px;overflow:auto;}

/*遮罩层*/
.overlay{position;absolute;top,right,bottom,left:0;b-g:rgba(0,0,0.5);z-index;}

http://ife.baidu.com/note/detail/id/662

参考链接

CSS 相对|绝对(relative/absolute)定位系列(一)
CSS 相对/绝对(relative/absolute)定位系列(二)
CSS 相对/绝对(relative/absolute)定位系列(三)
absolute元素在text-align属性下的对齐显示
absolute绝对定位的非绝对定位用法

posted @ 2017-03-05 20:10  changning  阅读(223)  评论(0编辑  收藏  举报