Css 定位解析

文档流:

        文档流,是指盒子按照 HTML 标签编写的顺序依次从上到下,从左到右排列,块元素占一行,行内元素在一行之内从左到右排列,先写的先排列,后写的排在后面,每个盒子都占据自己的位置。

定位分类:

我们可以使用 CSS 的 position 属性来设置元素的定位类型,position 的设置项如下:

  • static 默认值. 没有定位: 元素出现在正常的流中(忽略top, bottom, left, right 或者 z-index 声明)

  • relative 生成相对定位元素,一般是将父级设置相对定位,子级设置绝对定位,子级就以父级作为参照来定位,否则子级相对于body来定位。

  • absolute: 生成绝对定位元素,元素脱离文档流,不占据文档流的位置,可以理解为漂浮在文档流的上方,相对于上一个设置了定位的父级元素来进行定位,如果找不到,则相对于body元素进行定位。

  • fixed: 生成固定定位的元素,相对于浏览器窗口进行定位。

    元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

    定位元素的偏移

    定位的元素还需要用left、right、top或者bottom来设置相对于参照元素的偏移值。

    1. 相对定位:

CSS部分:
< style >
.con {
width: 300px;
height: 300px;
border: 1px solid black;
margin: 0px auto;
}

.con div {
width: 200px;
height: 70px;
margin: 10px;
}

.box01 {
background: lightgreen;
/* 设置相对定位 */
position: relative;
left: 50px;
top: 50px;
}

.box02 {
     background: lightskyblue
}

.box03 {
     background: lightpink;
}
< / style >


HTML部分:
<!-- .con>.box01+.box02+.box03 -->
< div class= "con" >
< div class= "box01" >1 </ div >
< div class= "box02" >2 </ div >
< div class= "box03" >3 </ div >
</ div >

2. 绝对定位:

< style >
.con{
width: 300px;
height: 300px;
border: 1px solid black;
margin: 0px auto;
/* 父级设置为相对定位,不设置偏移,子级就可以以它为参照做绝对定位 */
position: relative;
/* 设置父级的溢出隐藏 */
overflow: hidden;
}
.con div{
width: 200px;
height: 70px;
margin: 10px;
}
.box01{
background: lightgreen;
/* 设置绝对定位 */
position: absolute;
left: 131px;
top: 50px;
}
.box02{
background: lightskyblue
}
.box03{
background: lightpink;
}
< / style >
HTML部分:
<!-- .con>.box01+.box02+.box03 -->
< div class= "con" >
< div class= "box01" >1 </ div >
< div class= "box02" >2 </ div >
< div class= "box03" >3 </ div >
</ div >

3. 固定定位

< style >
.con{
width: 300px;
height: 300px;
border: 1px solid black;
margin: 0px auto;
}
.con div{
width: 200px;
height: 70px;
margin: 10px;
}
.box01{
background: lightgreen;
/* 设置固定定位 */
position: fixed;
right: 131px;
bottom: 50px;
}
.box02{
background: lightskyblue
}
.box03{
background: lightpink;
}
< / style >
HTML部分:
<!-- .con>.box01+.box02+.box03 -->
< div class= "con" >
< div class= "box01" >1 </ div >
< div class= "box02" >2 </ div >
< div class= "box03" >3 </ div >

</div>


猜你喜欢

转载自blog.csdn.net/oHenZiJue/article/details/80394812