定位属性position
在css中比较重要的便是position和float。
定位是将盒子定在某一个位置自由的漂浮在其他盒子的上面
定位的语法
定位=定位模式+边偏移(left right top bottom)
定位的属性值
1.静态定位 position: static;
相当于没有定位 设置边偏移无效
2.相对定位 position: relative;
1.相对于 自己原来在标准流中位置来移动的
2.不脱标(继续占有原来的位置,后面的盒子仍然以标准流的方式对待它)
3.绝对定位 position: absolute;
1.父元素没有定位,则以浏览器为准定位
2.祖先元素设置定位,参照的是最近的设置了定位(相对/绝对/固定)的祖先元素【一般子绝父相】
3.不保留原来的位置,完全是脱标的
4.固定定位 position: fixed;
1.始终参照的是浏览器窗口
2.不保留原来的位置,完全是脱标的
3.不会随着滚动条移动
5. 继承定位position: inherit;
1.继承父元素的position属性,但需要注意的是IE8以及往前的版本都不支持inherit属性
6. 粘性布局position: sticky;
例如:针对于position: sticky;
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div class="sticky">5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
</body>
---------------------------------------
<style>
div {
width: 100%;
height: 200px;
background-color: pink;
border: 1px solid #000;
font-size: 100px;
text-align: center;
line-height: 200px;
}
.sticky {
background-color: skyblue;
position: sticky;
top: 0;
}
</style>
元素居中的方式
在面试的时候经常会问到:
如何让一个元素在父元素中上下左右居中?
方式一:
<style>
.father {
width: 500px;
height: 500px;
background-color: pink;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
我们通常使用transform:translate(-50%,-50%)
--------------------------------------------
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
方式二:
父相子绝后,子元素所有的定位都设置为0,margin设置成auto
<style>
.father {
width: 500px;
height: 500px;
background-color: pink;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
------------------------------------------
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
方式三:
可以采用弹性盒子
<style>
.father {
width: 500px;
height: 500px;
background-color: pink;
display: flex;
align-items: center;
justify-content: center;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
-------------------------------------------
<body>
<div class="father">
<div class="son"></div>
</div>
</body>