我不是 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>
关于css - 何时准确使用相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37110201/