css定位属性的运用
css的定位属性主要是position属性的运用。
position的属性值(来确定定位方式【参照物】):
1:static 静态定位:
position的默认值,默认文本流的状态。
不会识别left right top bottom指定的坐标
2:absolute 绝对定位:
a : 参照物:按照已经有定位的父元素进行位置的变化。
b : 假如 当前没有父元素 或者 父元素没有定位的情况下,以整个文档为参照物。
c : 绝对定位,脱离文档流、不占据空间
例子:
代码:
.box{
width: 600px;
height: 600px;
background-color: royalblue;
position: relative;
}
.box-wrap{
width: 300px;
height: 300px;
background-color: sandybrown;
position: absolute;
top: 30px;
}
效果图:
3: relative 相对定位:
a : 参照物:自身默认的位置!
b : 始终占据空间,不会破坏文档流
例子:
代码:
.box{
width: 600px;
height: 600px;
background-color: royalblue;
position: relative;
top: 200px;
left: 200px;
}
效果图:
4:固定定位: position :fixed;
a : 参照物:浏览器窗口
b : 脱离整个文本流。不占据空间
例子:
代码:
.box{
width: 600px;
height: 600px;
background-color: royalblue;
position: fixed;
top: 200px;
left: 200px;
}
效果图:
5:黏性定位:position:sticky;
position:relative 和 position:fixed的结合。
如果页面没超出窗口范围,按照relative 执行
如果内容超出窗口位置,按照fixed执行。
例子:
代码
.box{
height: 60px;
background-color: royalblue;
position: sticky;
top: 0px;
}
.box-wrap{
height: 30px;
background-color: sandybrown;
}
效果图:
注意:
使用条件:
1、父元素不能overflow:hidden或者overflow:auto属性。
2、必须指定top、bottom、left、right4个值之一,否则只会处于相对定位
3、父元素的高度不能低于sticky元素的高度
4、sticky元素仅在其父元素内生效