【问题标题】:When to exactly use position relative何时准确使用相对位置
【发布时间】:2016-09-03 18:13:53
【问题描述】:

我不是 css 方面的专家。我没有给出任何职位并且有css之类的

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

#myId{
    position: relative;
    left: 10px;
    top: 10px;
}

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

【问题讨论】:

  • 为什么有 2400 个代表的人会问这样的问题?
  • 因为也许他正在学习新东西并且是其他方面的专家?
  • 是的,因为他是 Pradeep。基本上是一个网络开发人员。完全在 Drupal 的 LAMP Stack 上工作。
  • LAMP 和 CSS 有什么关系?显然他是后端开发人员,而不是前端。

标签: css css-position


【解决方案1】:

案例 1

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

案例 2

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

案例 3

您想将一个元素放在另一个元素上。静态元素不会对z-index 生效,所以需要将其位置设置为relativestaticfixed

可能还有其他用例


.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>

【讨论】:

  • 案例2也可以通过使用margin right来完成,并且它仍然在dom flow中而不使用position relative??
  • @Hacker 相对移动元素不会影响周围元素(将保持其占用空间不变)白色负边距也会影响周围元素。
  • @Hacker 检查第二个例子
猜你喜欢
  • 2020-12-07
  • 2015-08-15
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多