为什么不必要时设置相对位置

时间:2017-04-12 19:17:43

标签: html css css3 position

我看到很多网站在块元素中设置position: relative;时不会在内部元素中使用位置。有没有其他理由设置相对位置?

示例:

<div class="parent">
  <div class="parent__container">
    other elements here.
  </div>
</div>

.parent {
  background-color: blue;
}

.parent__container {
  position: relative;
  // etc
}

并且内部元素没有使用位置,有时我甚至会看到设置了position: relative;的.parent。

这是非常常见的,我可以指出几个没有任何必要设置位置的网站(至少我认为)。

感谢。

2 个答案:

答案 0 :(得分:1)

为什么将元素设置为position: relative

基本上有三个原因
  1. 重新定位元素本身,即top: 20px

  2. 在该元素上使用z-index。副作用,如果没有设置z-index,它仍会将自己定位在静态定位的元素之上。

  3. 限制绝对定位的子元素的范围,因此相对定位元素的子元素可以绝对定位在该块中。

  4. 以下是一篇描述最常用位置值之间差异的旧文章:

答案 1 :(得分:0)

如今大多数网站都使用“相对”定位来使其网站灵活,并与智能手机和非16x9兼容设备等小屏幕设备兼容。使用相对超过绝对定位的最初目的是允许程序员允许网页基于分层顺序处理定位,除非程序员另有说明。

编辑:请注意,通过定义“relative”,它会在DOM模型中为元素及其子元素提供一定的层次顺序;它不一定告诉元素如何定位自己(也就是知道左对齐或右对齐),而是创建一个“盒子”或“容器”,其中元素及其子元素基于其嵌套在其中嵌套。 HTML文档整体必须符合的HTML。换句话说,“relative”用其父项定义元素的优先级/层次结构。

相反,如果程序员想要静态定位某些元素,他们会使用“position:absolute;”使该元素相对于其父元素是静态的。例如:

    <div class="parentA">ParentA Text
      <div class="childA">
          All elements become positioned absolutely, requiring defined positions using margins, alginment and etc. Note that this may or may not be inherited depending on the browser and the code.
      </div>
    </div>
    <div class="parentB">ParentB Text
      <div class="childB">
          All elements become positioned relatively, requiring no defined positions using margins, alginment and etc, unless desired. This makes the webpage very flexible (dynamic in the position of its elements).
      </div>
    </div>
    <div class="parentC">ParentC Text
      <div class="childC">
          All elements in and under childC become positioned absolutely relative to parentC, requiring defined positions using margins, alginment and etc.
          <div class="grandChildC">
          Grandchild
          </div>
      </div>
    </div>
    <style>
    .parentA {
        position: absolute;
    }
    
    .parentB {
        position: relative;
    }
    
    
    .parentC {
        margin: 60px;
    }
    .childC {
        position: absolute;
    }
    </style>

如上所述,由于parentB是相对的,所以它从parentA停止的任何地方开始。由于父A没有大小并被定义为绝对/静态对象,因此两个div重叠。相反,由于partentC是相对的而childC是绝对的,childC将移动到parentC所在的任何位置,但是,它的轮廓将保持静态并且位于其他元素之上,即相对于parentC的位置静态。

我希望这能回答你的问题。如果没有,请更清楚你要提出的问题。