标题图
学习 CSS 相关知识, 定位是其中的重点, 也是难点之一, 如果不了解 css 定位有时候都不知道怎么用, 下面整理了一下关于定位属性的具体理解和应用方案.
一: 定位
定位属性列表
- position
- top
- bottom
- right
- left
- z-index
- position
基本语法:
position:static | absolute | fixed | relative
语法介绍:
static: 默认值, 无特殊定位.
absoulte: 相对于其最近的一个定位设置的父对象进行绝对定位, 可用 left,right,top,bottom.
fixed: 生成绝对定位的元素.
relative: 生成相对定位的元素, 可通过 left,right,top,bottom 属性设置相对于自身偏移位置.
代码:
- div { position:relative; top:-4px }
- bottom
基本特殊: 定位元素
基本语法: bottom:auto | length
语法
auto: 默认值, 无特殊定位.
length: 长度值 | 百分比, 必须定义 position 的属性值为 absolute 或者 relative 才有效.
代码:
- div { position:relative; bottom:6px; }
- z-index
语法: z-index:auto | number
取值: auto: 默认值, number: 无单位的整数值, 可负数.
代码:
- div { position:absolute; z-index:5; width:6px; }
- left
基本语法: left:auto | length
auto: 默认值, 无特殊定位.
length: 长度值 | 百分比, 必须定义 position 的属性值为 absolute 或者 relative 才有效.
代码:
- div { position:relative; top:-3px; left:6px; }
- top
基本语法: top:auto | length
auto: 默认值, 无特殊定位.
length: 长度值 | 百分比, 必须定义 position 的属性值为 absolute 或者 relative 才有效.
代码:
- div { position:relative; top:-3px; left:5px;}
- right
基本语法: right:auto | length
auto: 默认值, 无特殊定位.
length: 长度值 | 百分比, 必须定义 position 的属性值为 absolute 或者 relative 才有效.
代码:
div { position:relative; top:-3px; right:6px}
相对定位
relative 生成相对定位的元素, 相对于其它位置进行定位.
代码:
- <style type="text/css">
- #box1 {
- margin: 10px;
- width: 100px;
- height: 100px;
- background-color: blue;
- }
- #box2 {
- margin: 10px;
- width: 100px;
- height:100px;
- background-color: red;
- /*position: relative;
- left: 100px;
- top: 100px;*/
- }
- </style>
- <div id="box1"></div>
- <div id="box2"></div>
绝对定位
绝对定位相对于它的参照物移动位置, 如果没有, 默认为 body 为参照物.
结语
带你走进 CSS 定位详解, 多试试, 熟能生巧嘛~
小礼物走一走 or 点赞
送
来源: http://www.jianshu.com/p/9216bd12e610