尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

绝对定位VS相对定位 postion:absolute relative

绝对定位VS相对定位 postion:absolute relative 绝对定位VS相对定位对比维度relative相对定位absolute绝对定位参考点往哪移参照物是自己原本在文档流中的位置即它没移动前本该在的地方。参照物是最近的那个position值不为static默认值的祖先元素。如果往上找都找不到则相对于浏览器视口body。是否脱离文档流不脱离。它原来的物理空间坑位被牢牢霸占着周围元素无法挤占。完全脱离。它原来的坑位立刻消失周围元素会无视它直接补位上来这会导致父元素高度塌陷。对兄弟元素影响移动它top/left不会影响周围元素的位置周围元素不动它盖在别人上面。移动它会影响周围元素因为坑位没了周围元素重新排列。典型使用场景1. 微调元素位置比如图标上移 2px。2.作为absolute子元素的“锚点”父级设relative子级设absolute。1. 弹窗、下拉菜单、悬浮按钮。2. 在父容器内进行自由拖拽定位。场景假设 HTML 中有三个兄弟盒子A、B、C都是纵向排列。场景 Arelative给 B 设置position: relative; top: 20px;。B往下移动了 20px视觉上压住了 C。但 B原来的空白坑位依然保留所以 C 不会往上移动依然被堵在 B 的原始位置下方。结果就是 B 和 C 重叠了。场景 Babsolute给 B 设置position: absolute; top: 20px;。B彻底消失了脱离文档流。原来的坑位没了C会立刻往上窜填补 B 的位置。如果父容器只有 A、B、C 三个子元素父容器的高度会瞬间失去 B 的支撑变为 0 这就是高度塌陷浮动和绝对定位都会引发塌陷。使用注意“子绝父相”的原理我们通常给父元素加position: relative;且不设置偏移量top/left目的不是为了移动父元素而是单纯地让父元素成为一个“定位锚点”让子元素的absolute局限在父盒子内部活动。例子:!DOCTYPE html html head meta charsetutf-8 title菜鸟教程(runoob.com)/title style /style /head body !-- 父元素设 relative作为约束盒子 -- div styleposition: relative; width: 300px; height: 200px; background: #eee; !-- 子元素设 absolute相对于父元素的左上角定位 -- div styleposition: absolute; right: 10px; bottom: 10px; width: 50px; height: 50px; background: red; 我在右下角 /div /div /body /html# 注意绝对定位的“隐藏规则”定位属性top/bottom/left/right默认值是auto。而auto并不代表是 0auto的官方解释其他三个right top bottom的解释也是如此。也就是说如果一个元素设置了绝对定位postion:absolute,并且没有设置left以及right中的任意一个此时left及right默认值为auto,那么auto的水平方向具体位置则是元素没有设置postion:absolute时的位置即是定位为默认值positon:static时的位置。垂直方向上同理。但是当父元素为display:flex弹性盒子时此时的位置有所不同见下文示例!DOCTYPE html html head meta charsetutf-8 title/title /head style .grandparent { width: 600px; height: 600px; background: antiquewhite; } .parent { width: 300px; height: 300px; background: aquamarine; float: right; } .son1 { width: 200px; height: 200px; background: cornflowerblue; } .son2 { width: 200px; height: 200px; background: fuchsia; position: absolute; } /style body div classgrandparent div classparent div classson1/div div classson2/div /div /div /body /html特殊情况当父元素.parent为弹性盒子display:flex时子元素.son2设置为position:absoluetop bottom left right为默认auto时.son2的位置会发生变化。演示给.parent加上displayflex!DOCTYPE html html head meta charsetutf-8 title/title /head style .grandparent { width: 1000px; height: 600px; background: red; } .parent { width: 600px; height: 300px; background: aquamarine; float: right; display: flex; } .son1 { width: 200px; height: 200px; background: cornflowerblue; } .son2 { width: 200px; height: 200px; background: fuchsia; } /style body div classgrandparent div classparent div classson1/div div classson2/div /div /div /body /html运行效果同样给.son2加上position:absolute效果如下按照之前的“绝对定位的隐藏规则”因为没有设置top/bottom/right/left,默认值为auto,所以即使.son2加上postion:absolute位置仍然是没有加时position:static默认的位置不会发生变化如上图。 但是实际运行效果如下原因针对父元素为弹性盒子display:flexcss规范中指出了子元素为postion:absolute时在计算静态位置时会忽略同级元素的存在。css规范链接https://drafts.csswg.org/css-flexbox/#abspos-items
返回列表