我在 CSS 方面不是很专业。我没有指定任何位置,CSS 如下:
#myId{
margin-left: 10px;
margin-top: 10px;
}
#myId{
position: relative;
left: 10px;
top: 10px;
}
这两个选项都能实现我想要的效果。那么何时应该使用相对定位?和其他定位方式相比有什么优缺点呢?
我在 CSS 方面不是很专业。我没有指定任何位置,CSS 如下:
#myId{
margin-left: 10px;
margin-top: 10px;
}
#myId{
position: relative;
left: 10px;
top: 10px;
}
这两个选项都能实现我想要的效果。那么何时应该使用相对定位?和其他定位方式相比有什么优缺点呢?
案例1
你有一个内部元素,其定位为absolute
,想要将该元素粘附到其父元素上。那么你需要在父元素上应用position: relative
。默认情况下,绝对定位的元素不会遵循DOM流动,并从最近的相对定位元素(默认为HTML)获取位置。
案例2
你想移动元素,但仍然保持它在DOM流中。那么应用position: relative
并使用left
/right
/top
/bottom
属性来移动它。
案例3
你想将一个元素放置在另一个元素上方。静态元素不会受到z-index
的影响,因此你需要将其位置设置为relative
、static
或fixed
可能还有其他用例
.a {
background-color: #ddd;
left: 50px;
top: 150px;
position: relative;
width: 200px;
height: 200px;
text-align: center;
}
.absolute,
.a div {
position: absolute;
left: 50px;
top: 50px;
width: 100%;
height: 60px;
background-color: rgba(250, 0, 0, .4);
}
<div class="a">
HTML > relative
<div>HTML > relative > absolute</div>
</div>
<div class="absolute">HTML > absolute</div>
.a {
position: relative;
left: -20px;
}
.b {
margin-left: -20px;
}
.wrapper {
border-bottom: 2px solid #454545;
}
<div class="wrapper">
relative moving content
<br/>
<span>some content to overlap</span>
<span class="relative a">some content</span>
<span>some content</span>
</div>
<div class="wrapper">
using margins
<br/>
<span>some content to overlap</span>
<span class="relative b">some content</span>
<span>some content</span>
</div>
position
属性允许您通过相对于自身的位置(相对定位),另一个已定位元素(如其父元素是定位的)(绝对定位)或相对于视口的位置(固定定位)来指定元素在 DOM 中的位置。任何已定位元素都不在“流”中,因此它的存在不会直接影响那些未定位的元素。已定位的元素还可以享受使用z-index
属性的好处。请参阅此文章。 - zer00ne