在网页布局中,我们常用的布局的方法有普通方式、浮动(float)方式、定位(position)方式。普通方式就是上下排列的布局、浮动方式就是左右排列的布局、定位方式就是层叠(叠加)排列的布局。而今天我们就来说说定位布局。
定位的属性:position :检索或设置对象的定位方式。而position它有5个属性值,分别为static、relative、absolute、fixed、sticky。
第一个属性值是:static:默认值;没有定位;这个属性值可以用于取消元素之前的定位设置。
第二个属性值:relative:相对定位。(参照物:自己所在的位置)
相对定位(relative)的特点
1、 如果没有定位偏移量,对元素本身没有任何影响
2、不使元素脱离文档流,空间是会被保留。
3、不影响其他元素布局
4、 left、top、right、bottom是相对于当前元素自身进行偏移的 ,不能独自存在,必须配合定位元素一起使用
代码如下:
<div class="box1">我是盒子1</div>
<div class="box2">我是盒子2并且我用了relative</div>
<div class="box3">我是盒子3</div>
.box1{
width: 200px;
height: 100px;
background: red;
}
.box2{
width: 200px;
height: 50px;
background: pink;
position: relative;
top: 100px;
left: 100px;
}
.box3{
width: 200px;
height: 100px;
background: yellow;
}
效果图
第三个属性值:absolute : 绝对定位 (参照物:包含块—该元素的祖先级元素)
特点:
1、使元素完全脱离文档流
2、使内联元素支持宽高 (让内联具备块特性)
3、使块元素默认宽根据内容决定(让块具备内联的特性)
4、 如果有定位祖先元素相对于定位祖先元素发生偏移,没有定位祖先元素相对于整个文档发生偏移(绝对、相对、固定)
代码如下:
<div class="box1">我是盒子1</div>
<div class="box2">我是盒子2并且也是盒子3的父亲
<div class="box3">
我是盒子3,我用了absolute,并且我是盒子2的儿子
</div>
</div>
.box1{
width: 200px;
height: 100px;
background: red;
}
.box2{
width: 300px;
height: 300px;
background: pink;
position: relative;
}
.box3{
width: 200px;
height: 100px;
background: yellow;
position: absolute;
top: 30px;
left: 200px;
}
效果图:
第四个属性值: 固定定位: fixed (参照物:始终都是 相对于整个浏览器窗口进行固定定位的)
特点:
1、使元素完全脱离文档流
2、使内联元素支持宽高 (让内联具备内联块特性)
3、使块元素默认宽根据内容决定(让块具备内联块的特性)
4、相对于整个浏览器窗口进行偏移,不受浏览器滚动条的影响不会受到祖先元素的影响。
代码如下:
<div class="box1">我是盒子1
<div class="box2">
我是盒子2,我用了fixed
</div>
</div>
.box1{
width: 800px;
height: 1000px;
background: red;
}
.box2{
width: 300px;
height: 300px;
background: pink;
position: fixed;
top: 200px;
left: 200px;
}
效果图
第五个属性值: 黏性定位: sticky
特点:在没有到达指定位置的时候,是没有定位效果的,到达了指定位置,就变成了固定模式。
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<div class="box1">我就定在这里了</div>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
<p>粘性定位</p>
.box1{
width: 100px;
height: 100px;
background: red;
position: sticky;
top: 0;
}
效果图: