问题
看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 100px;
height: 100px;
background-color: #bfa;
}
.box2{
width: 100px;
height: 100px;
background-color: orange;
}
.box3{
width: 100px;
height: 100px;
background-color: orchid;
}
</style>
</head>
<body>
<div class="box1">1</div>
<div class="box2">2</div>
<div class="box3">3</div>
</body>
</html>
如果想把box2移动到box1右边,而box3不动,怎么做呢?
可以设置box2和box3的margin。
.box2{
width: 100px;
height: 100px;
background-color: orange;
margin-top: -100px;
margin-left: 100px;
}
.box3{
width: 100px;
height: 100px;
background-color: orchid;
margin-top: 100px;
}
但是这样就很麻烦,得设置两个box,如果用浮动来实现,也很复杂。
因此,得用定位来随意摆放box2而不动其他的元素。
定位是一种更加高级的布局手段,可以将元素摆放在页面的任意位置。
position
可选值:
static:默认值,元素是静止的,没有开启定位
relative:开启元素的相对定位
absolute:开启元素的绝对定位
fixed:开启元素的固定定位
sticky:开启元素的粘滞定位
相对定位
position:relative
如果不设置偏移量,元素不发生任何变化。
那何为偏移量(offset)?
偏移量可以设置元素的位置。
有:
top:元素与定位位置上面的距离
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: relative;
top: 50px;
}
bottom:元素与定位元素下边的距离。
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: relative;
bottom: 50px;
}
肯定有人疑惑,两个都设置,会咋样
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: relative;
top: 50px;
bottom: 50px;
}
显然,top有效,bottom无效。因为可以设置负值,所以通常用一个就行了。
left:元素和定位位置左侧的距离。
right元素和定位位置右侧的距离。
这里就不解释了,和top、bottom类似。
解决问题
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: relative;
top: -100px;
left: 100px;
}
定位位置
前面说的定位位置是什么?
定位位置是元素在文档流中的位置,也就是开启定位前的那个位置。
相对定位会提升元素的层级
从前面的效果可以看到,如果重叠了,是box2覆盖其他的box,所以box2的层级较高。
相对定位不会使回溯脱离文档流
虽然层级提升,但是它没有脱离文档流,否则box3就上去了。
相对定位不会改变元素的性质
块还是块,行内还是行内