何时准确使用相对位置

Hac*_*ker 3 css css-position

我在 css 方面不是很专家。我没有给出任何位置并且有像

#myId{
    margin-left: 10px;
    margin-top: 10px;
}

#myId{
    position: relative;
    left: 10px;
    top: 10px;
}
Run Code Online (Sandbox Code Playgroud)

两者都做了我想要的。我什么时候应该准确使用相对位置。与其他相比有什么优势或劣势?

Jus*_*nas 5

情况1

您有定位的内部元素,absolute并希望该元素坚持它的父元素。比您应用于position: relative父元素。默认情况下,绝对元素从 DOM 流中弹出并从最近的相对元素(默认为 html)中获取位置

案例二

您想移动元素但仍将其保留在 DOM 流中。比应用position: relative和移动它left/ right/ top/bottom属性。

案例3

您想将一个元素放在另一个元素上。静态元素不会生效,z-index这就是为什么您需要将其位置设置为relativestatic或者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);
}
Run Code Online (Sandbox Code Playgroud)
<div class="a">
  HTML > relative
  <div>HTML > relative > absolute</div>
</div>

<div class="absolute">HTML > absolute</div>
Run Code Online (Sandbox Code Playgroud)

.a {
  position: relative;
  left: -20px;
}
.b {
  margin-left: -20px;
}
.wrapper {
  border-bottom: 2px solid #454545;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)