对position错误的理解
每次做层浮动效果时,我都将position设置为absolute, 再通过js来计算left,top来给元素来定位。也许是之前做的页面非常简单,整个页面里面没有嵌套设置position的情况,故一直都认为当position:absolute时,是相对于document.body来偏移的, 其实并不是这样的, 我们先看下position的属性。
position的属性
static
relative
absolute
fixed
对每个属性的理解
static: 这是默认值,即按照正常的文档流的顺序来放元素。 这个时候你设置left,top是没有效果的。
relative: 位置会以元素本身的位置进行偏移,即你设置了left,top ,他会以此元素原来的位置做为坐标偏移。
absolute: 位置会从父元素开始查找,如果父元素的position不是 static的,那么他就以这个父元素的位置进行偏移,否则就会一直向上查找,直至查找到body,就以body的位置偏移,所以以前理解absolute是以body为位置偏移是错的,那是因为你处理的元素的父元素的position都是默认static的, 但当你的父元素是非static的,算位置时就出现不一样的效果。
fixed: 这个才是以document.body的位置偏移的, 无论你要设置的元素的父元素或往上的元素的position是absolute,relative,fixed, 他都是以document.body的位置偏移的。
这样理解后,就消除了以前的一些疑惑。 但在定位方面,我们可以试一下更复杂的情况。
可以进一步理解
在实际position定位时会遇到很多种情况,比如父元素设置了margin,padding,class="tags" href="/tags/BORDER.html" title=border>border. 那么定位原则是怎样的呢?
1. 当元素的position:relative时,位置偏移时是从此元素自身的margin的最左上侧开始算的。
2. 当元素的position:absolute时 这里也分两种情况:
(1) 无论它的父元素是怎样的,如果它自身有margin ,那么他的位置偏移也是要算上它自身的margin的。
(2) 如果它的父元素不是默认的static ,而它父元素有class="tags" href="/tags/BORDER.html" title=border>border 和 padding, margin.
则它的位置偏移要算上父元素的margin和class="tags" href="/tags/BORDER.html" title=border>border,当时不会算上padding.
可能上面说的比较有点乱,不太好理解,在这里上个例子,大家也可以改这个例子来看看效果,例子仅仅只是测试位置,命名和文字请不要太在意。
class="language-html"><!DOCTYPE>
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<style>
class="tags" href="/tags/DIV.html" title=div>div {
class="tags" href="/tags/BORDER.html" title=border>border:1px solid red;
}
.ap {
position:relative;
class="tags" href="/tags/BORDER.html" title=border>border:30px solid red;
margin:200px;
padding:20px;
left:20px;
top:20px;
width:400px;
height:400px;
}
.a {
class="tags" href="/tags/BORDER.html" title=border>border:1px solid blue;
position:absolute;
margin:100px;
left:0px;
top:0px;
}
</style>
</head>
<body>
<class="tags" href="/tags/DIV.html" title=div>div>
fdsfdsds
<class="tags" href="/tags/DIV.html" title=div>div>
qq
<class="tags" href="/tags/DIV.html" title=div>div class="ap">
fffdfdfd<br>
<class="tags" href="/tags/DIV.html" title=div>div class="a">kkkk</class="tags" href="/tags/DIV.html" title=div>div>
</class="tags" href="/tags/DIV.html" title=div>div>
</class="tags" href="/tags/DIV.html" title=div>div>
</class="tags" href="/tags/DIV.html" title=div>div>
<script>
</script>
</body>
</html>
总结
现在终于基本上对position的定位有一定的了解了,也希望可以帮助到大家,如果有什么问题请给我留言,大家一起进步。 另外,对于position还会结合到通过js操作dom元素的
offsetWidth,offsetLeft, offsetParent等等属性,下一期我会继续讨论这方面的问题,希望大家一起将这些吃透。
注: fixed是相对浏览器窗口的定位,而不是body
子class="tags" href="/tags/DIV.html" title=div>div设置position:absolute 父class="tags" href="/tags/DIV.html" title=div>div如果是默认定位,子class="tags" href="/tags/DIV.html" title=div>div的参照不是这个父class="tags" href="/tags/DIV.html" title=div>div了,而是body.
如果父class="tags" href="/tags/DIV.html" title=div>div是默认定位,它还会继续查找父class="tags" href="/tags/DIV.html" title=div>div的父有没有非默认定位,直至找到body.