一、设置定位属性后,盒子变为行内块,可以设置盒子宽高等;
二、不论设置定位与否,子盒子永远浮于父亲盒子前;
三、同级标签元素设置相同定位属性,后边盒子浮于前边盒子之上(根据标签盒子在HTML结构中的排版声明顺序),例:
1.设置兄弟盒子都为绝对定位或者固定定位(效果相同)
<style>
.father {
width: 100px;
height: 100px;
background: #ff0;
}
.box1 {
width: 50px;
height: 100px;
background: #f00;
line-height: 180px;
}
.box2 {
width: 60px;
height: 50px;
background: #0ff;
line-height: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
观察效果:
1.不设置定位的效果:
2.给两个兄弟子标签设置绝对(absolute)定位或固定(fixed)定位效果(两个属性想过相同):
代码:
<style>
.father {
width: 100px;
height: 100px;
background: #ff0;
/* position: absolute; */
}
.box1 {
width: 50px;
height: 100px;
background: #f00;
line-height: 180px;
position: absolute;
}
.box2 {
width: 60px;
height: 50px;
background: #0ff;
line-height: 50px;
position: absolute;
}
</style>
</head>
<body>
<div class="father">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
查看效果:
说明:在设置定位属性后,定位盒子会脱离文本流出现上浮效果,有异于float浮动的浮动,上层盒子会完全盖住下层盒子(包括文本),而对于float的浮动,上层只会盖住下层盒子背景,但是会和下层文本共层,从而出现文本环绕的效果(float浮动设计初衷——文本环绕图片样式)。
这里没有将relative相对定位拿出来的原因是,相对定位出现效果会有差异,但是原理大同小异(推测)
- relative相对定位:给两兄弟共同设置相对定位属性:
<style>
.father {
width: 100px;
height: 100px;
background: #ff0;
/* position: absolute; */
}
.box1 {
width: 50px;
height: 100px;
background: #f00;
/* top: 10px; */
line-height: 180px;
position: relative;
}
.box2 {
width: 60px;
height: 50px;
background: #0ff;
line-height: 50px;
position: relative;
}
</style>
</head>
<body>
<div class="father">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
观察效果:
可以看到相对定位后,两个盒子层次似乎没有改变,还是独行显示,那是否相对定位不会使布局脱离文本流呢?答案是否定的
首先,对于相对relative定位的概念是,盒子相对于当前位置通过top,bottom等属性改变位置,而当前并没有改变位置,故不会移位,也就看不出效果,不像fixed和absolute分别起始都是居于屏幕坐标和浏览器页面坐标的原点(即屏幕左上角),移位也是居于屏幕和浏览器页面;
所以我们移位试试,设置box1 top:10px;,查看效果: