知识点--单做备忘,基础要扎实才行

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