知识点--单做备忘,基础要扎实才行
body有默认的8px-margin;
运行下面代码
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"> sonsonsonsonsonsonsonsonson <div id="div4"></div> </div> </div> </div> <div id="center"></div> <style> *{ margin:0; padding:0; } body{ margin:40px; border:60px solid #0C6; padding:20px; } #div1{ border:20px solid #00e; margin:10px; background:#f00; } #div2{ position:absolute; left:10px; top:40px; border:10px solid #f00; margin:10px; padding:10px; background:#666; color:#fff; } #div3{ position:absolute; left:40px; top:40px; margin:10px; padding:10px; /*border:20px solid #fee;*/ } #div4{ margin:20px; border:100px; } #center{ position:absolute; width:100px; height:100px; background:#000; left:50%; top:50%; margin-left:-50px; margin-top:-50px; } </style> <script> //position:absoulte的offsetLeft指从有相对定位或者有绝对定位的父元素的margin-sizing开始的; //如果元素没有定位,是根据文档流布局,那么文档的offsetLeft为;子元素的border-sizing到有一个定位的margin-sizing; //offsetLeft就是指从子元素的border-sizing到 一个有定位的父元素的marin-sizing,所以如果要获取一个内层元素的offsetLeft的时候要小心,并且如果某一个绝对定位的父元素有margin,因为你获取的 offsetLeft += offsetParent.offsetLeft, 会比实际的长; //margin会影响到 绝对定位的元素,所有就有了负边距居中这种东西; //负边距居中这种东西虽然影响布局有点奇怪,但是,得出的offsetLeft的确是正确的;刚刚好在中间,因为offsetLeft就是不包含margin进行计算的; //用这个 e5.getBoundingClientRect() 也好用; var e1 = document.querySelector("#div1"); var e2 = document.querySelector("#div2"); var e3 = document.querySelector("#div3"); var e4 = document.querySelector("#div4"); var e5 = document.querySelector("#center"); </script> </body> </html>
天道酬勤
本文作者:方方和圆圆
本文链接:https://www.cnblogs.com/diligenceday/p/3952097.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步