- HTML中文网
- 联系QQ:88526
- QQ交流群

- 微信公众号

CSS Position(定位)
position 属性指定了元素的定位类型,它具有五个值:
static
relative
fixed
absolute
sticky
元素可以使用的top、bottom 、left 、right属性来定位,然而,这些属性单独是无法工作,必须先设定position属性。他们也有不同的工作方式,这取决于定位方法
static 定位
HTML元素的默认值,即没有定位,元素出现在正常的流中
静态定位的元素不会受到 top, bottom, left, right影响
div{ width:100px; height: 100px; background-color: pink; position: static; }
点击 "运行实例" 按钮查看在线实例
效果图:
fixed 定位
元素的位置相对于浏览器窗口是固定位置。
即使窗口是滚动的它也不会移动:
div{ width:100px; height: 100px; background-color: pink; position: fixed; top:40px; }
点击 "运行实例" 按钮查看在线实例
效果图:
注意:Fixed 定位在 IE7 和 IE8 下需要描述 !DOCTYPE 才能支持。
Fixed定位使元素的位置与文档流无关,因此不占据空间。
Fixed定位的元素会和其他元素重叠
relative 定位
相对定位元素的定位是相对与其它正常位置的元素
.box1, .box2{ width:100px; height: 100px; background-color: pink; } .box2{ position:relative; top:10px; left:30px; }
点击 "运行实例" 按钮查看在线实例
效果图:
absolute 定位
绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于<html>
.box1, .box2{ width:100px; height: 100px; background-color: pink; border: 2px solid #444; } .box2{ position:absolute; top:40px; left:30px; }
点击 "运行实例" 按钮查看在线实例
效果图:
sticky 定位
sticky 英文意思是粘贴,所以可以把它称之为粘性定位。
它基于用户的滚动位置来定位。
粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。
它的行为就像相对定位,而当页面滚动超出目标区域时,它的表现就像fixed定位,它会固定在目标位置。
元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。
这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
注意: Internet Explorer, Edge 15 及更早 IE 版本不支持 sticky 定位。 Safari 需要使用 -webkit- prefix
body{ height: 2000px; } .box1, .box2{ width:100px; height: 100px; background-color: pink; border: 2px solid #444; } .box2{ position: -webkit-sticky; /* Safari */ position: sticky; top:0px; background-color:pink; border: 2px solid #444;}
点击 "运行实例" 按钮查看在线实例
效果图:
属性 | 描述 | 值 | CSS版本 |
bottom | 定义了定位元素下外边距边界与其包含块下边界之间的偏移。 | aut olength %inherit | 2 |
clip | 剪辑一个绝对定位的元素 | shap eauto inherit | 2 |
cursor | 显示光标移动到指定的类型 | url auto crosshair default pointermove e-resize ne-resize nw-resize n-resize se-resize sw-resize s-resize w-resize text wait help | 2 |
left | 定义了定位元素左外边距边界与其包含块左边界之间的偏移。 | auto length % inherit | 2 |
overflow | 设置当元素的内容溢出其区域时发生的事情。 | auto hidden scroll visible inherit | 2 |
overflow-y | 指定如何处理顶部/底部边缘的内容溢出元素的内容区域 | auto hidden scroll visible no-display no-content | 2 |
overflow-x | 指定如何处理右边/左边边缘的内容溢出元素的内容区域 | auto hidden scroll visible no-display no-content | 2 |
position | 指定元素的定位类型 | absolute fixed relative static inherit | 2 |
right | 定义了定位元素右外边距边界与其包含块右边界之间的偏移。 | auto length % inherit | 2 |
top | 定义了一个定位元素的上外边距边界与其包含块上边界之间的偏移。 | auto length % inherit | 2 |
z-index | 设置元素的堆叠顺序 | number auto inherit | 2 |
推荐手册