您的位置:首页 > 其它

子元素要绝对定位时,父元素应该怎么办?

2015-12-09 21:13 239 查看
问题:

如果子元素设置绝对定位(absolute),父元素需要设置相对定位(relative),否则子元素就不知道会飘到哪去了。

本着知其然还要知其所以然的学习态度,就去Google了,得到了一些见解,以下:

一、表

实现子元素在父元素中的绝对定位必须满足以下两个条件:

1、父元素要有相对定位属性(position:relative),

2、子元素设置绝对定位(position:absolute),并且同时加四个方向(top,bottom,left,right)的任意方向的属性值

<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8" />
<title></title>
<style type="text/css">
#main{
width:500px;
height:600px;
border:1px solid black;
position:relative;
background:pink;
}
#one,#two{
width:100px;
height:100px;
}
#one{
background:blue;
position:absolute;
top:100px;
left:100px;
}
#two{
background:yellow;
position:absolute;
top:200px;
left:200px;
}
</style>
</head>
<body>
<div id="main">
<div id="one">1</div>
<div id="two">2</div>
</div>
</body>
</html>


这个理解应该是从代码的书写形式总结的,虽然能满足页面要求,但其实是有谬误的。具体看下面分析。

二、里

子元素的绝对定位是包含块“containing block”的知识,

在 10.1 节 (http://www.w3.org/TR/CSS2/visudet.html#containing-block-details) 提到:
The position and size of an element's box(es) are sometimes
calculated relative to a certain rectangle, called thecontaining
block
of the element.

在下面的详细定义中,分情况说明了具有不同 position 属性的元素如何确定 containing block,其中第 4 点是绝对定位元素的情况:

If the element has 'position: absolute', the containing block is
established bythe nearest ancestor with a 'position' of 'absolute', 'relative'
or 'fixed'
, in the following way:

In the case that the ancestor is an inline element, the containing
block is the bounding box around the padding boxes of the first and
the last inline boxes
generated for that element. In CSS 2.1, if the inline
element is split
across multiple lines, the containing block is undefined.

Otherwise, the containing block
is formed by the padding edge of

the ancestor.

If there is no such ancestor, the containing block is theinitial
containing block
.

从这里可以看到,一个元素的 containing block 是由其最近的 position 为 absolute / relative / fixed 的祖先元素决定的。

如果没有找到,则为 initial containing block。需要注意 initial containing block 并不是所谓的以 <body> 或是 <html> 定位的。

对这个 initial containing block 规范前文有描述:
The containing block in which the root element lives is a rectangle called the initial containing block. For continuous
media,it has the dimensions of the viewport and is anchored at the
canvas origin
; ...

这就是说,initial containing block 是以整个 canvas (渲染内容的空间, http://www.w3.org/TR/CSS2/intro.html#canvas) 的坐标原点(左上)为基准,以 viewport (也就是浏览器视窗内渲染 HTML 的空间)为大小的矩形。

所以平时说的 position:absolute 元素相对最近的 position 为 absolute / relative / fixed 的祖先元素,或在找不到时基于根元素定位,这后面一半是错误的。

综上,子元素的绝对定位是相对于最近的position为absolute/relative/fixed的祖先元素,找不到时就相对于初始块(initial containing block)定位。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: