CSS定位布局
结合便宜属性调整元素的显示位置
. 属性:position
. 取值:可取relative(相对定位), absolute(绝对定位)/fixed(固定定位)
position: relative/absolute/fixed
. 便宜属性:设置定位的元素可以使用便宜属性调整距离参照物的位置;
. position代码展示:
div{
position: relative;
width: 200px;
height: 200px;
background-color: red;
/* 相对定位 以自己原本的位置为参照物 */
/* 不会脱离默认布局方案 保留原始位置 */
/* 一般用于对页面元素的微调 */
/* 偏移属性 left bottom right top */
/* 取正数值 向相反方向移动
取负数值 向相同方向移动
*/
/* left:-100px;
bottom: 100px; */
/* left: 500px; */
top: 100px;
}
p{
width: 200px;
height: 200px;
background-color: blue;
}
absolute绝对定位:
1. 绝对定位的元素参照离他最近的已经定位的祖先元素进行偏移,如果没有,则参照窗口进行偏移
2. 绝对定位的元素会脱流,在文档中不占位,可以手动设置宽高
使用绝对定位 : “父相子绝” : 父元素设置相对定位,子元素绝对定位,参照已定位的父元素偏移.
#parent{
width: 300px;
height: 250px;
background-color: aqua;
margin: 0 auto;
/* 为子元素做参照物 */
position: relative;
}
/* 11:03~11:18 */
#parent>div{
/* position: relative;
left: 200px;
top: 150px; */
/* 绝对定位 */
/* 参照物 距离最近的 已定位的 祖先元素 */
/* 如果没有参照物 默认参照窗口定位 */
/* 在父元素中调整子元素位置时 */
position: absolute;
width: 100px;
height:100px;
background-color: brown;
right: 0;
bottom: 0;
}
堆叠次序
元素发生堆叠时可以使用 z-index 属性调整已定位元素的显示位置,值越大元素越靠上:
- 属性 : z-index
- 取值 : 无单位的数值,数值越大,越靠上
- 堆叠:
- 定位元素与文档中正常元素发生堆叠,永远是已定位元素在上
- 同为已定位元素发生堆叠,按照 HTML 代码的书写顺序,后来者居上
div{
width: 200px;
height: 200px;
background-color: red;
/* margin-top: 100px; */
position: relative;
z-index: 999;
}
p{
width: 300px;
height: 200px;
background-color: blue;
margin-top:-100px;
position: relative;
z-index: 100;
}