在下面的代码中,
<div class="box" id="one">One</div>
<div class="box" id="two">Two</div>
<div class="box" id="three">Three</div>
<div class="box" id="four">Four</div>
Run Code Online (Sandbox Code Playgroud)
.box {
display: inline-block;
background: red;
width: 100px;
height: 100px;
float: left;
color: black;
}
#one{
background: red;
}
#two {
position: absolute;
background: yellow;
}
#three{
background: green;
}
#four{
background: blue;
}
Run Code Online (Sandbox Code Playgroud)
-
盒子"两个"绝对定位并且远离文件的流动,盒子"三"和"四"代替盒子"两个",由此,盒子"两个"被移位作为最后一个元件,如图所示下面,看起来不错,
但是在下面的代码中,
<div id="parent-div">
<div id="default">Default</div>
<div id="centered">Centered</div>
<div id="centered-text">Centered Text</div>
</div>
<div id="top-left-pos">Top Left
</div>
<div id="another-pos">Another pos
</div>
Run Code Online (Sandbox Code Playgroud)
#parent-div{
background: #B3bEb5;
border: 0.1em solid black;
}
#default{
background: #DBE9F4;
}
#centered{
background: #89CFF0;
width: 50%;
margin: auto;
}
/* text-align: left, right, center, justify */
#centered-text{
text-align: center;
}
/* Absolute Positioning : Positioning Based on the Document */
#top-left-pos{
background: #89CFF0;
border: 0.1em solid black;
position: absolute;
width: 200px;
height: 100px;
float:left;
}
#another-pos{
background: #FF0000;
border: 0.1em solid black;
float: left;
width: 190px;
height: 110px;
}
Run Code Online (Sandbox Code Playgroud)
top-left-pos
元素绝对定位并远离文档的流动,another-pos
元素确实取代top-left-pos
元素但不替换top-left-pos
元素?而是another-pos
元素在top-left-pos
元素下面呈现,如下所示,为什么top-left-pos
不移位,不像盒子"两个"的第一个场景?
浮动和位置如何协同工作?
他们没有.绝对定位的元素不能浮动.浮动元素不能绝对定位.
当一个元件被指定到两个浮子和 position: absolute
,后者有优先权,而元件不不浮动.尽管不相关,但float: left
您的第一个场景优先于其他场景display: inline-block
.该规范有一个完整的小节,详细说明了如何display
,position
并float
一起工作.
为什么
top-left-pos
没有流离失所,不像盒子"两个"的第一个场景?
因为第一个场景中的框"两个"被浮动元素取代.在第二个场景中,没有浮动来替换该元素.你所拥有的只是两个绝对定位的元素,彼此没有意识到.