一、CSS定位的作用?
CSS中的定位使用来布局的熟练应用对页面美化有很好的帮助,下面就进行详细介绍:定位分为静态定位,相对定位,绝对定位,固定定位这四种,定位有不同的参数,例如:left、right、top、bottom、z-index等。
二、具体定位介绍
1、静态定位(static)
一般的标签元素不加任何定位属性都属于静态定位,在页面的最底层属于标准流。
代码如下(示例):
<div class="static"></div>
.static {
position: static;
border: 3px solid #73AD21;
}
2、绝对定位(absolute)
1.相对于最近的定位祖先元素进行定位(而不是相对于视口定位,如 fixed)。
2.如果绝对定位的元素没有祖先,它将使用文档主体(body),并随页面滚动一起移动。
3.绝对定位元素可层叠,层叠顺序可通过 z-index 属性控制,z-index值为无单位的整数,大的在上面,可以有负值。
代码如下(示例):
<div class="box3">没有父元素或者祖元素,以浏览器为定位</div>
<div class="father">
<div class="son">如果有父元素,但父元素没定位,还是以浏览器为定位</div>
</div>
<div class="grandfather">
<div class="father1">
<div class="son1">如果有父元素,父元素有定位,还是以最近一级有定位祖先元素为定位</div>
</div>
</div>
.box3 {
/*3.绝对定位,相对他父元素或者祖元素的位置。
1.如果没有父元素或者祖元素,以浏览器为定位 position:absolute; */
position: absolute;
/* left: 10px;
top: 10px; */
top: 100px;
right: 0;
width: 100px;
height: 100px;
background-color: purple;
}
/*如果有父元素,但父元素没定位,还是以浏览器为定位*/
.father {
width: 500px;
height: 500px;
background-color: skyblue;
}
.son {
position: absolute;
width: 200px;
height: 200px;
left: 0;
bottom: 0;
background-color: tomato;
}
/*2.如果有父元素,父元素有定位,还是以最近一级有定位祖先元素为定位*/
.grandfather {
position: relative;
width: 800px;
height: 800px;
background-color: hotpink;
padding: 50px;
}
.father1 {
width: 500px;
height: 500px;
background-color: rgb(33, 172, 45);
}
.son1 {
position: absolute;
width: 200px;
height: 200px;
left: 20px;
bottom: 30px;
background-color: rgb(41, 44, 194);
}
/*3.绝对定位不再占用原先的位置(脱标)。*/
效果图(示例):
3、相对定位(relative)
1.元素相对于其正常位置进行定位。
2.设置相对定位的元素的 top、right、bottom 和 left 属性将导致其偏离其正常位置进行调整。
代码如下(示例):
.box1 {
/*2.相对定位,相对他原来的位置 position:relative; */
position: relative;
top: 100px;
left: 100px;
width: 200px;
height: 200px;
background-color: pink;
}
<div class="box1"></div>
4、固定定位(fixed)
1.固定定位与绝对定位类似,但它是相对于浏览器窗口定位,并且不会随着滚动条进行滚动。
2.固定定位不在占用原先的位置。
代码如下(示例):
.dj {
position: fixed;
top: 0;
right: 0px;
}
<div class="dj">
<img src="images/pvp.png" alt="">
</div>
5、粘性定位(sticky)(了解)
- 以浏览器的可视窗口为参照点移动元素(固定定位特点)
- 粘性定位占有原先的位置(相对定位特点)
- 必须添加 top 、left、right、bottom 其中一个才有效