<p>当需要一个元素不以文档流规则定位的时候,应该使用position这个属性</p><ul> <li>static是position的默认属性值</li> <li>relative是相对自身定位</li> <li>absolute是相对第一个position的非static的祖先定位</li> <li>fixed是相对浏览器窗口定位</li> <li>stick粘性定位</li></ul><p>要实现定位,除了设置定位参照元素之外,还需要top,right,bottom,left来具体描述定位</p>
relative - 相对自身
<style> .d2{ position: relative; top: 10px; left: 20px; height: 50px; width: 50px; border: 1px solid black; }</style><body> <p>当需要一个元素不以文档流规则定位的时候,应该使用position这个属性</p> <ul> <li>static是position的默认属性值</li> <li>relative是相对自身定位</li> <li>absolute是相对第一个position的非static的祖先定位</li> <li>fixed是相对浏览器窗口定位</li> <li>stick粘性定位</li> </ul> <p>要实现定位,除了设置定位参照元素之外,还需要top,right,bottom,left来具体描述定位</p> <div id="parent"> <div class="d1"> <div class="d2">如果一个元素使用relative定位,相对自身原来的位置定位,对文档流没有影响</div> <div class="d3">d3</div> </div> <button>按钮1</button> <button>按钮2</button> </div></body>
absolute - 相对父元素
<style> .d1{ position: relative; height: 300px; width: 300px; border: black 1px solid; } .d2{ position: relative; height: 100px; width: 100px; border: red 1px solid; } .d3{ position: absolute; right: 0; bottom: 0; height: 50px; width: 50px; border: green 1px solid; } </style><body> <p>如果一个元素如果需要相对他的非static的祖先元素定位,设置position为absolute</p> <div class="d1"> <div class="d2"> <div class="d3"></div> </div> </div></body>
fixed - 相对窗口
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>fixed</title> <style> /* 块级元素的position如果为absolute或是fixed的时候,默认宽为0 */ .d1{ position:fixed; } .s1{ position: absolute; } </style></head><body> <div class="d1"></div> <span class="s1"></span></body></html>
z-index - 层级
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .d1{ position: absolute; z-index: 6; opacity: .5; /*透明度*/ width: 300px; height: 300px; background-color: pink; } .d2{ position: absolute; z-index: 3; width: 200px; height: 200px; background-color: salmon; } .d3{ position: absolute; z-index: 6; width: 100px; height: 100px; background-color: brown; } </style></head><body> <p>如果一个元素脱离了文档,那么他和其他文档流元素就不在一个平面上</p> <div class="d1"></div> <div class="d2"></div> <div class="d3"></div></body></html>