当容器的position属性值为absolute时,这个容器即被绝对定位了。使用绝对定位的容器,会脱离文档流。
当有多个绝对定位容器放在同一个位置时,显示哪个容器的内容呢?类似Photoshop的图层有上下关系,绝对定位的容器也有上下的关系,在同一个位置只会显示最上面的容器。在计算机显示中把垂直于显示屏幕平面的方向称为z方向,CSS绝对定位的容器的z-index属性对应这个方向,z-index属性的值越大,容器越靠上。即同一个位置上的2个绝对定位的容器只会显示z-index属性值较大的。
如果容器设置了绝对定位,但是其父容器没有设置position 属性,绝对定位的容器会一直往上查找,直到找到具有position属性的容器。如果没有设置不到定位的父亲容器,以浏览器窗口为定位参考点
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>水平垂直居中</title><style>.parent{width: 200px;height: 200px;background-color: red;position: relative;}.child{width: 100px;height: 100px;background-color: pink;/* position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto; *//* 方案二 */position: absolute;top: 50%;left: 50%;margin-top: -50px;margin-left: -50px;}</style></head><body><div class="parent"><div class="child"></div></div></body></html>
/* 实现水平垂直居中两种方法
1、子元素绝对定位,父元素相对定位,并且给
子元素设置定位属性全部为0 margin为auto
2、子元素绝对定位,父元素相对定位
并且给子元素设置定位属性
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;*/