position定位得几种方式
static(没有定位)是position的默认值,元素设置相对于原本位置的定位,
元素并不脱离文档流,因此元素原本的位置会被保留,其他的元素位置不会受
到影响
这是相对定位是指给元素设置相对于原本位置的定位,元素并不脱离文档流,因此元素原本的位置会被保留,其他的元素位置不会受到影响,一般配上position:absolute来使用俗称父相子决
absolute(绝对定位)是指给元素设置绝对的定位,相对定位的对象可以分为两种情况:
1)、设置了absolute的元素如果存在有祖先元素设置了position属性为relative或者
absolute,则这时元素的定位对象为此已设置position:reative属性的祖先元素
2)、如果并没有设置了position:relative属性的祖先元素,则此时相对于body进行定位
这是固定定位是基于body来定位得不管怎么滑动拥有这个属性得元素会象是一颗钉子一样固定不动
position:sticky
position 属性中最有意思的就是sticky了,设置了sticky的元素,在屏幕范围
(viewport)时该元素的位置并不受到定位影响(设置top、left等属性无效),
当该元素的位置将要移除偏移范围时,定位又会变成fixed,根据设置的left、top等属性固定位置的效果
不管怎么滑动他就会在那不动
实例效果如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.top,
.foot {
width: 100%;
height: 200px;
background: red;
border: 1px solid black;
}
.sticky {
width: 100%;
height: 100px;
position: sticky;
top: 0;
background-color: green;
}
</style>
</head>
<body>
<div class="top"></div>
<div class="top"></div>
<div class="top"></div>
<div class="sticky"></div>
<div class="foot"></div>
<div class="foot"></div>
<div class="foot"></div>
<div class="foot"></div>
<div class="foot"></div>
</body>
</html>
元素水平、居中的几种方法
一个元素的剧中
// dom结构
<div class='box'>
<div class='small_box'></div>
</div>
方法一: 子绝父相,top:50%,left:50%,子需要移动本身宽度和高度的一般
.box {
width:400px;
height:400px;
background:red;
position:relative
}
.small_box {
width:200px;
height:200px;
background:yellow;
// 子元素绝对定位,top 50% left 50%之后是中间的小盒子的最左边居中了
position:absolute;
left:50%;
top:50%;
// 可以使用向左向上移动本身宽度和高度的一半(下面的两行)
// 也可以使用 transform:translate(-50%,-50%)
margin-left:-100px;
margin-top:-100px
}
父元素设置成弹性盒子,子元素横向居中,纵向居中
.box {
width: 400px;
height: 400px;
background: red;
display: flex;
align-items: center;
justify-content: center;
}
.small_box {
width: 200px;
height: 200px;
background: yellow;
}
子绝父相,子元素所有定位为0,margin设置auto自适应
.box {
width: 400px;
height: 400px;
background: red;
position: relative;
}
.small_box {
width: 200px;
height: 200px;
background: yellow;
position: absolute;
top: 0;
left: 0;
right: 0;
botttom: 0;
margin: auto;
}