## 元素如何定位 **考察点** 1. position有哪些值及其作用 2. 文档流和脱离文档流的概念 3. 如何解决元素重叠 **回答** 1. position有4个值,分别是`static`,`relative`, `absolute`, `fixed`. 一般元素的默认值是`static`. `relative` 是相对定位,相对该元素本来应该在的位置偏移,偏移后可能和其他正常元素重叠,并且其原来所占空间不能被其他元素占用。 `absolute`是绝对定位, 相对于 static 定位以外(即relative,absolute和fixed)的第一个父元素进行定位。设置成absolute之后,元素将会脱离文档布局,即该元素在页面中并不占有位置,而是显示在正常元素的上层或者下层。 `fixed`是相对浏览器视窗定位,页面滚动时,`fixed`定位的元素相对浏览器视窗的位置始终不变。设置成fixed之后,元素将会脱离文档布局,即该元素在页面中并不占有位置,而是显示在正常元素的上层或者下层。 2. 文档流在文档中元素排列时会占用位置,脱离文档流在元素排列时并不占有位置。一般设置了`position: absolute`, `position: fixed`, `float: left`, `float: right`的元素为脱离文档流,其余可显示元素则为文档流。 3. 设置`z-index`可以控制元素所在的层。 有趣的是,z-index:0时,非文档流仍然显示在文档流的上层,但是z-index:-1时, 非文档流显示在文档流的下层,因此可以得出结论, 文档流并不是z-index为0 `relative`相对定位 ![](https://box.kancloud.cn/2015-12-13_566d21bfe079d.gif) `relative`在位置偏移中位置优先级`left`>`right`, `top`>`bottom`, 代码证明 ```css .relative1{ position: relative; left: 20px; top: 20px; background-color: orange; width:300px; } .relative2{ position: relative; left: 20px; top: 20px; right: 20px; bottom: 20px; width:300px; background-color: orange; } .relative3{ position: relative; right: 20px; bottom: 20px; width:300px; background-color: orange; } .relative4{ position: relative; right: 20px; bottom: 20px; left: 20px; top: 20px; width:300px; background-color: orange; } ``` ```html <div style="background:green; "> <div>hello world</div> <div class="relative1">relative 1</div> <div>hello world</div> <div>hello world</div> <div class="relative2">relative 2</div> <div>hello world</div> <div>hello world</div> <div>hello world</div> <div class="relative3">relative 3</div> <div>hello world</div> <div>hello world</div> <div>hello world</div> <div class="relative4">relative 4</div> </div> ``` 结果: ![](https://box.kancloud.cn/7c373fff5125587146f00c9b1b508f14_443x313.PNG) 详细代码: http://js.jirengu.com/sedij/3/ `absolute`绝对定位,top和bottom,left和right没有优先级之分,设置之后会拉大元素的宽和高。 ```css .abs1{ position: absolute; left: 40px; top: 10px; background-color:red; } .abs2{ position: absolute; left: 40px; top: 10px; right: 40px; bottom: 10px; background-color:red; } ``` ```html <div style="background:green;height:100px;">正常文档流, 这里没有absolute的元素</div> <div style="background:blue;height:100px;"> 正常文档流 <div class="abs1">absolute 1</div> </div> <div style="background:green;height:100px;position:relative"> 正常文档流 <div class="abs1">absolute 1</div> </div> <div style="background:blue;height:100px;position:relative"> 正常文档流 <div class="abs2">absolute 1</div> </div> ``` 结果 ![](https://box.kancloud.cn/3a66b39f9bf1241a9313d47b9d78d851_465x413.PNG) 详细代码 http://js.jirengu.com/yezix/2/ `fixed`在位置偏移中位置优先级`left`>`right`, `top`>`bottom`, 代码证明: ```css .fixed1{ background-color: red; width:100px; height: 100px; position: fixed; top: 10px; left: 50px; right: 50px; bottom: 50px; } ``` ```html <div style="width:100%;height:300px;background-color: green;"> <div class="fixed1"></div> </div> ``` ![](https://box.kancloud.cn/9cfc498bd33cb2dc45c541249963a7c2_458x311.PNG) 详细代码 http://js.jirengu.com/biwuj/2/