定位 position:
元素加了postion 为非static以后top,left,right,bottom 就可以生效。
left 和 right 只能用一个。
top 和 bottom 只能用一个。
用position 可以让元素重叠。当元素设置了非static定位以后,可以用z-index跳转元素显示层级。z-index 可以给正整数和负整数,数字越大,显示越靠前。
- absolute: 绝对定位,相对于第一个非static定位的上(父)级元素,脱离文档流。如果没有找到这种元素,就是相对于窗口。位置会随滚动条滚动。
- relative: 相对定位, 相对于元素自身的位置进行设定。也是脱离文档流,但是元素原来的位置还会留着。
- fixed : 固定定位 相对于窗口位置变化,不会随滚动条滚动,脱离文档流。
- sticky:粘性定位 默认是relative的效果,当滚动到要超出屏幕之外时变成fixed。
<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <a href="#">连接</a> <div class="box0"> <div class="box1"> <div class="box2"> </div> <span> span1 </span> </div> </div> <div class="box2-fx"></div> <nav class="box2-nav"></nav>
body {
height: 5000px;
}
ul {
margin: 0;
padding: 0;
/* list-style-type: georgian;
list-style-position: inside;
list-style-image: url(./商城首页/images/c1.jpg); */
list-style: circle inside;
}
a,ul{
/* 鼠标的样式 */
cursor: pointer;
}
.box0 {
position: relative;
width: 300px;
height: 300px;
border: 1px solid blue;
}
.box1 {
/* position: relative; */
margin: 0 auto;/*添加了position:absolute就失效了*/
width: 200px;
height: 200px;
border: 1px solid red;
}
.box2 {
/* absolute relative脱离文档流 */
position: absolute;
top: 30px;
left: 50px;
/* position: relative;
top: 10px;
left: 10px; */
width: 100px;
height: 100px;
background-color: green;
}
/* 固定定位 */
.box2-fx {
position: fixed;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: black;
}
/* 粘性定位 默认是relative效果 要超出屏幕之外时自动变为fixed */
.box2-nav {
/* absolute relative脱离文档流 */
position: sticky;
margin-top: 50px;
top: 0;
/* position: relative;
top: 10px;
left: 10px; */
height: 100px;
background-color: green;
}