今天的内容是关于 position 布局,这种布局以前使用的比较多,现在逐步进入了衰退期,但是有些需求使用它实现非常便捷。使用 css 中的 position 属性可以让元素脱离流式布局,使其按照自己特有的方式进行布局,比如让某个元素始终停到可视区域的顶部,让某个元素停靠在某个元素的右边。我认为 position 的作用就是要把某个元素放到特定的位置,为了更方便地把某个元素放到指定的位置,它提供了多个值 relative、absolute、fixed、sticky。
刚开始的时候,我看到很多人在乱用 position,不管需不需要都加一个 position: relative 或 position: absolute,而且 relative 和 absolute 分不清。利用这次机会要学懂 position 的使用。今天主要学习 relative 的使用。
relative 是相对布局,它的关键点是「相对谁」,通过 top、left、right、bottom 来修改元素的偏移位置,这 4 个属性在流式布局中并不会起作用,首先要确定元素的起点坐标是什么,top、left、right、bottom 就是要告诉元素它距离起点坐标的位置。相对谁?相对的是元素在流式布局中的起始位置,起始位置就是元素在流式布局的位置。属性 top 和 bottom 、left 和 right 不能同时使用,那么同时使用这两个属性会有什么后果呢?
<body>
<div class="box">
<p>前端小课,每日一课</p>
<p>素燕,公众号</p>
<p>前端从0-1</p>
</div>
</body>
p:nth-child(2) {
background-color: blue;
position: relative;
right: 20px;
left: 10px;
}
结果发现如果同时使用 left 和 right ,left 的优先级会更高,right 不起作用。同样看一看 top 和 bottom:
p:nth-child(2) {
background-color: blue;
position: relative;
bottom: 10px;
top: 20px;
}
top 的优先级会高于 bottom 的,同时设置 top 和 bottom,bottom 会会起作用。其实按照正常思维考虑,这种设计非常合理,既设置了 left 又设置了 right,浏览器会说:“你究竟让我从那边移动?”。relative 的坐标系如下,上边为正,下边为负;左边为负,右边为正:
其实 top 和 bottom 可以达到同样的效果,比如向上移动 20px,可以使用 top: 20px,也可以使用 bottom: -20px;
relative 的一大特点就是「不会破坏」默认的流式布局,也就是说,你可以让某个元素移动到指定位置,但是你在流式布局中的「坑位」还会保留,如果你想回来,不会没有你的位置,这个位置永远为你保留。举个例子:
<style>
* {
margin: 0;
padding: 0;
}
.box {
margin: 10px;
height: 400px;
background-color: #eeeeee;
}
p {
color: white;
font-size: 18px;
line-height: 40px;
}
p:nth-child(1) {
background-color: red;
}
p:nth-child(2) {
background-color: blue;
position: relative;
top: 20px;
left: 30px;
}
p:nth-child(3) {
background-color:black;
}
</style>
<body>
<div class="box">
<p>前端小课,每日一课</p>
<p>素燕,公众号</p>
<p>前端从0-1</p>
</div>
</body>
上面的代码使用了:
p:nth-child(2) {
background-color: blue;
position: relative;
top: 20px;
left: 30px;
}
使第二个孩子 p 元素向上移动了 20px,向左移动了 30px,但是原先的流式布局任然保留。预览效果如下:
总结
总之 ,position: relative 的作用就是在不打破流失布局的前提下,让元素移动到某一个位置。关于 position:absolute 的使用我们在下一节课程讨论。
今天的有效打卡指令:
1. position 属性都有哪些值?
2. relative 有哪些应用场景?
3. position 布局的缺点。
第4天:图解 FlexBox 布局(下)