admin管理员组文章数量:1611195
一 咱们先来看下W3C上的定义:
1 position 属性把元素放置到一个静态的、相对的、绝对的、或固定的位置中。注意:static和relative仍然占据标准流的位置。
static 默认。位置设置为 static 的元素,它始终会处于页面流给予的位置(static 元素会忽略任何 top、bottom、left 或 right 声明)。
relative 位置被设置为 relative 的元素,可将其移至相对于其正常位置的地方,因此 “left:20” 会将元素移至元素正常位置左边 20 个像素的位置。
absolute 位置设置为 absolute 的元素,可定位于相对于包含它的元素的指定坐标。此元素的位置可通过 “left”、”top”、”right” 以及 “bottom” 属性来规定。
fixed 位置被设置为 fixed 的元素,可定位于相对于浏览器窗口的指定坐标。此元素的位置可通过 “left”、”top”、”right” 以及”bottom” 属性来规定。不论窗口滚动与否,元素都会留在那个位置。工作于 IE7(strict 模式)。
二 重点来看absolute :
1 当父元素设置了除static定位之外的定位的时候,(也就是说父元素可以是absolute relative ),子元素相对于父元素定位,可是相对于父元素哪里定位呢?这个时候,基准是父元素的内容区(也即是content(width+height)+padding区域,不包括border和margin。
2 当父元素没有设置定位的时候,子元素相对于body进行定位。
3 子元素定位的边界是包括子元素的 整体 = margin + border + padding + content ;的margin外边界为基准进行定位。
三 代码解析:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position</title>
<style type="text/css">
.one{
width: 980px;
height: 300px;
margin: 0 auto;
background-color: pink;
}
.two {
height: 200px;
width: 400px;
float: left;
background-color: blue;
/*padding-left: 100px;*/
margin-left: 100px;
position: relative;
border: 30px solid green;
}
.three{
position: absolute;
width: 15px;
height: 15px;background-color: red;
/*left: 0;
left: 20px;
left: -20px;
bottom: 10px;*/
}
</style>
</head>
<body>
<div class="one">
<div class="two">
<div class="three"> </div>
</div>
</div>
</body>
</html>
该案例重点理解子元素定位的基准,当父元素设置了除static定位之外的定位的时候,子元素相对于父元素定位,可是相对于父元素哪里定位呢?这个时候,基准是父元素的内容区(width+height)+padding,不包括border和margin
四 浏览器窗口显示
坐标以content+padding左上角伟基准
红色的盒子 three 是absolute定位,其基准是蓝色的盒子 two 的content和padding区 ,并不包括 border(绿色部分)。
版权声明:本文标题:position定位的基准问题 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728607120a1165595.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论