同时使用 `position: absolute` 和 `float: left` 时的预期行为是什么?
What is the expected behavior when both `position: absolute` and `float: left` is used?
一起使用position: absolute
和float:left
看起来有点混乱甚至荒谬,因为position: absolute
不会影响兄弟元素的位置,而float:left
会影响兄弟 float 元素的位置。
但是,在 CSS 中允许同时使用它们,那么预期的行为是什么?我不太确定同时使用它们时会发生什么,因为 MDN 文档中没有描述 (https://developer.mozilla.org/en-US/docs/Web/CSS/float)。
有没有人对此有任何想法?谢谢!
将 float:left;
添加到 absolute
定位元素显然不会添加元素的任何行为更改。大多数 display
属性也是如此。例如,添加 display:inline;
不会导致其维度丢失。
它也没有显示与相邻浮动元素的任何联系。
.box{
border: 1px solid red;
float: left;
height: 100px;
width: 100px;
}
.box1{
border: 1px solid green;
height: 100px;
width: 100px;
position: absolute;
display: table;
}
<div class="box"></div>
<div class="box1"></div>
但是当去掉相邻元素的float
时,绝对定位的元素定位在它的下面
.box{
border: 1px solid red;
height: 100px;
width: 100px;
}
.box1{
border: 1px solid green;
height: 100px;
width: 100px;
position: absolute;
display: table;
}
<div class="box"></div>
<div class="box1"></div>
在CSS2规范中讨论(https://www.w3.org/TR/CSS2/visuren.html#dis-pos-flo):
Otherwise, if
'position' has the value 'absolute' or 'fixed', the box is absolutely
positioned, the computed value of 'float' is 'none', and display is
set according to the table below. The position of the box will be
determined by the 'top', 'right', 'bottom' and 'left' properties and
the box's containing block.
所以结论是当position
的值为absolute
时,float
被强制设置为none
。
一起使用position: absolute
和float:left
看起来有点混乱甚至荒谬,因为position: absolute
不会影响兄弟元素的位置,而float:left
会影响兄弟 float 元素的位置。
但是,在 CSS 中允许同时使用它们,那么预期的行为是什么?我不太确定同时使用它们时会发生什么,因为 MDN 文档中没有描述 (https://developer.mozilla.org/en-US/docs/Web/CSS/float)。
有没有人对此有任何想法?谢谢!
将 float:left;
添加到 absolute
定位元素显然不会添加元素的任何行为更改。大多数 display
属性也是如此。例如,添加 display:inline;
不会导致其维度丢失。
它也没有显示与相邻浮动元素的任何联系。
.box{
border: 1px solid red;
float: left;
height: 100px;
width: 100px;
}
.box1{
border: 1px solid green;
height: 100px;
width: 100px;
position: absolute;
display: table;
}
<div class="box"></div>
<div class="box1"></div>
但是当去掉相邻元素的float
时,绝对定位的元素定位在它的下面
.box{
border: 1px solid red;
height: 100px;
width: 100px;
}
.box1{
border: 1px solid green;
height: 100px;
width: 100px;
position: absolute;
display: table;
}
<div class="box"></div>
<div class="box1"></div>
在CSS2规范中讨论(https://www.w3.org/TR/CSS2/visuren.html#dis-pos-flo):
Otherwise, if 'position' has the value 'absolute' or 'fixed', the box is absolutely positioned, the computed value of 'float' is 'none', and display is set according to the table below. The position of the box will be determined by the 'top', 'right', 'bottom' and 'left' properties and the box's containing block.
所以结论是当position
的值为absolute
时,float
被强制设置为none
。