css定位
定位:将盒子定在某一个位置,所以定位也是在摆放盒子,按照定位的方式移动盒子。
定位=定位模式+边偏移。
定位模式:用于指定一个元素在文档中的定位方式;边偏移决定了该元素的最终位置。
相对定位(position: relative;)
<style>
.box1 {
position: relative;
top: 100px;
left: 10px;
width: 200px;
height: 200px;
background-color: pink;
}
.box2 {
width: 200px;
height: 200px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
绝对定位(position: absolute;)
如果没有父元素,或父元素无定位,则以浏览器为准则。
如果上级有定位,则以最近一级的父元素为参考移动位置。
绝对定位不在占有原来的位置。
<style>
.box1 {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.box2 {
position: absolute;
left: 0;
bottom: 0;
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
固定定位(position: fixed;)
1、以浏览器的可视窗口为参考点移动元素。
和父元素没有关系,不会随着滚动条滚动。
2、固定定位是脱标的,可以看作是特殊的绝对定位,不占有原来的位置
<style>
.box1 {
width: 800px;
height: 1400px;
background-color: pink;
margin: 0 auto;
}
.box2 {
position: fixed;
left: 50%;/* 浏览器宽度一半 */
margin-left: 400px;
width: 50px;
height: 150px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="box2">版心盒子</div>
<div class="box1">固定定位盒子</div>
</body>