该文章总结自张鑫旭慕课,以及自己的使用经验和建议。
绝对定位absolute使用建议
建议无依赖相对定位
relative
来使用,需要用到偏移的时候用到margin
值来实现,同时,没有依赖的绝对定位偏移的基础是<u>原来的包含块</u>。
<u>无依赖绝对定位</u>的特性:
位置跟随(此时绝对定位的元素是不占据任何空间的,注意在
ie6&ie7
下绝对定位会把元素inline-block
化)
使用注意:
- 绝对定位中``````可以消去空格,保证完美的贴合
- 由于绝对定位脱离文档流的属性,动画尽量作用在绝对定位的元素上。
无依赖绝对定位的应用:
- 利用
margin
来进行图片偏移,更适合自适应布局 - 下拉框定位最佳实践(无依赖)
- 对齐居中或边缘
- 居中(并不是最佳实践)
使用text-align:center
和position: absolute;margin-left: -xxpx;
来实现<div style="text-align: center;"> //重点就是在这里 <img style="width: 200px;position: absolute;margin-left: -100px;"> <div>
- 边缘跟随最佳实践
与上面的例子相似,只不过用text-align:right;
,然后把边缘的那个div
设置为inline
(注意fix
和absolute
的区别,fix
其实算是绝对定位,只是它是根据于浏览器视窗口) - 溢出不换行(注册页面的
tip
提示)
- 居中(并不是最佳实践)
绝对定位z-index无依赖
误区:绝对定位元素都需要z-index
控制层级,确定其显示的垂直位置
- 如果只有一个绝对定位元素,自然不需要
z-index
,自动覆盖普通元素 - 如果两个绝对定位元素,控制
DOM
流的前后顺序达到需要的效果,依然无z-index
- 如果多个绝对定位交错,非常非常少见,
z-index: 1;
控制 - 如果非弹框类的绝对定位元素
z-index>2
,便是冗余
absolute与height、width的应用
注意:top,bottom,left,right
百分比是依赖于父元素的宽高的(如果没有限制的父元素就是整个文档)
-
全屏自适应黑色半透明遮罩层
html.body { height: 100%; } .overlay { position: absolute; width: 100%; height: 100%; left: 0; top: 0; }
或者(没有宽高也能实现)
.overlay { position: absolute; left: 0;top: 0;right: 0;bottom: 0; ... }
可见,如果绝对定位方向是对立的,结果是相互拉伸而不是瞬间位移。所以下面其实是等价的(拉伸和
width/height
相互代替)ie7+
position: absolute; left: 0;top: 0;bottom: 0;width: 50%; === position: absolute; left: 0;top: 0;bottom: 0;right: 50%;
其他的情况也是类似的。
-
如果想要制作一个遮罩层距离右边
200px
,可以这样实现.overlay { background-color: #000; position: absolute; right: 200px; top: 0; left: 0; bottom: 0; }
如果使用
width
,就必须用到css3
,这在兼容性上就大打折扣。.overlay { background-color: #000; position: absolute; top: 0; left: 0; bottom: 0; width: calc(100% - 200px);//存在兼容性问题 }
所以,这种拉伸的效果代替宽度有两个优点:
- 容器无需固定
width
和height
,内部也可以拉伸 - 容器拉伸,内部元素支持百分比
width/height
值
- 容器无需固定
-
如果拉伸属性和
width/height
同时存在,width/height
设置的尺寸会大于拉伸属性设置的尺寸
如:下面的宽度是50%
而不是100%
position: absolute;top: 0;left: 0;right: 0;bottom: 0;width: 50%;
相互合作性:
position: absolute;left: 0;right: 0;width: 50%;
此时,假设上面的代码给它加一句
margin: auto
,就能实现水平居中了。(ie8+
)
-
绝对定位居中
position: absolute;left: 0;right: 0;bottom: 0;top: 0;height: xxx;margin: auto;//必须有高度
可见,
top/bottom
与height
结合可以实现垂直居中,left/right
与width
结合可以实现水平居中
利用绝对定位实现WEB整体布局效果(总结)
- 做遮罩层
html,body {
height: 100%;
}//这里可以不需要
.overlay {
position: absolute/fixed;//覆盖整个document用fixed
top: 0;
left: 0;
right: 0;
bottom: 0;
}
-
各个模块各居其位(适合用于移动端开发,头尾固定中间显示信息,解决
ios
中fixed
兼容性问题)- 头尾
header,footer { position: absulote; //水平拉伸 left: 0; right: 0; } header { height: 48px; top: 0; } footer { height: 52px; bottom: 0; }
- 侧边栏
aside { width: 250px; position: absolute; left: 0; //高度百分之百拉伸 top: 0; bottom: 0; }
- 内容区域想象成body
content { position: absolute; top: 48px;//头部高度去除 bottom: 52px;//尾部高度去除 left: 250px;//如果有侧边栏的话 overflow: auto; }
- 全屏覆盖要与整个大容器平级(不是
content
而是整个大div
)
<!--全屏拉伸.overlay的css代码--> <div class="page"></div> <div class="overlay"></div>
水平垂直居中定位(略)