<style> body { margin: 0;/* 去掉浏览器默认的外边距8px */ } div { width: 200px; height: 200px; background-color: cyan; /* 开启绝对定位 1.当前元素脱离文档流 2.若是不设置位置的偏移量的话,位置不会有任何变化的 */ position: absolute; /* 设置定位的偏移量: * 水平方向正值 - 向右移动 * 水平方向负值 - 向左移动 * 垂直方向正值 - 向下移动 * 垂直方向负值 - 向上移动 */ top: 100px; left: 100px; } </style> </head> <body> <div></div> </body>
<style> body { margin: 0; height: 1000px; } #d1 { width: 200px; height: 200px; background-color: #83c44e; /* 开启固定定位 - 相对于浏览器窗口的定位 */ position: fixed; left: 100px; top: 100px; } #d2 { width: 200px; height: 200px; background-color: cyan; position: absolute; left: 500px; top: 100px; } </style> </head> <body> <div id="d1"></div> <div id="d2"></div> </body>
<style> body{ margin: 0; } #d1{ width: 200px; height: 200px; background-color: cyan; /* 外边距 */ margin: 100px; } #d2{ width: 100px; height: 100px; background-color: #ffac13; /* 外边距 */ margin-left: 100px; /* 相对定位是相对于自身元素原来的位置的定位 */ position: relative; left: 100px; } </style> </head> <body> <div id="d1"> <div id="d2"></div> </div> </body>
定位的方式解析图:浏览器
<style> body{ margin: 0; } div{ width: 200px; height: 200px; } #d1{ background-color: cyan; /* 开启绝对定位 */ position: absolute; /* 开启定位后设置偏移量 */ left: 150px; top: 150px; z-index: 2323; } #d2{ background-color: #ffac13; /* 开启相对定位 */ position: relative; /* 开启定位后设置偏移量 */ left: 50px; top:50px; z-index:1; } /* 必须是当前元素开启定位的状况下,z-index属性才会有效 当多个属性设置z-index属性时 - 值大的会覆盖值小的 */ </style> </head> <body> <div id="d1"></div> <div id="d2"></div> </body>
堆叠分析图:布局
备注: 继承中有一个inherit值 - 就是是继承于祖先元素属性的意思,当子级元素的属性设置inherit值时表明继承父级元素使用的属性值.字体
<style> /* CSS的样式属性: 1. 可继承的属性 - 指定元素的样式,同时做用其后代元素 2. 不可继承的属性 - 只能做用在指定的元素 */ body{ /* 页面中的默认的字体大小为 16px 页面中的默认的颜色为黑色 */ font-size: 148px; color: cyan; } p{ /* inherit值 - 是继承于祖先元素属性的意思 当前样式属性的值是继承于祖先元素 */ font-size: inherit; } </style> </head> <body> <p>一花一世界,一叶一孤城</p> </body>
继承于层叠分析图spa