定位(待完善)

定位的想法:允许我们覆盖基本文档流的基本行为

  • 静态定位:position:static
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>定位</title>
  <style>
    .positioned{
      position: static;
      background: blue;
    }
  </style>
</head>
<body>
  <p class="positioned">Lor officia deserunt mollit anim id est laborum.</p>
</body>
</html>

加不加css,效果除了颜色变化,没有任何变化!所以可以知道:静态定位是默认行为


  • 相对定位:它与静态定位非常相似,占据在正常的文档流中,除了你仍然可以修改它的最终位置,包括让它与页面上的其他元素重叠。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>定位</title>
  <style>
    .positioned{
      position: relative;
      background: blue;
      top:30px;
      left:30px;
    }
  </style>
</head>
<body>
  <p class="positioned">Lor officia deserunt mollit anim id est laborum.</p>
</body>
</html>

有相对定位,(相对于默认)。必须有left, right, top, bottom其中一个
相对定位工作的方式——你需要考虑一个看不见的力,推动定位的盒子的一侧,移动它的相反方向。 所以例如,如果你指定 top: 30px;一个力推动框的顶部,使它向下移动30px。


  • 绝对定位:绝对定位的元素不再存在于正常文档布局流程中。相反,它坐在它自己的层独立于一切。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>定位</title>
  <style>
    .positioned{
      position: absolute;
      background: blue;
      top:30px;
      left:30px;
    }
  </style>
</head>
<body>
  <p class="positioned">Lor officia deserunt mollit anim id est laborum.</p>
</body>
</html>

top,bottom,left和right以不同的方式在绝对定位。 它们指定元素应距离每个包含元素的边的距离,而不是指定元素应该移入的方向。 所以在这种情况下,我们说的绝对定位元素应该位于从“包含元素”的顶部30px,从左边30px。


  • 固定定位:
    这与绝对定位的工作方式完全相同,只有一个主要区别——绝对定位固定元素是相对于 元素或其最近的定位祖先,而固定定位固定元素则是相对于浏览器视口本身。 这意味着您可以创建固定的有用的UI项目,如持久导航菜单。

  • z-index
    z-index 值影响定位元素位于该轴上的位置——正值将它们移动到堆栈上方,负值将它们向下移动到堆栈中。默认情况下,定位的元素都具有z-index为auto,实际上为0。

position: sticky:
有一个新的定位值可用称为 position: sticky,尚未广泛支持。 这基本上是相对位置和固定位置之间的混合,其允许定位的元件像它被相对定位一样动作,直到其滚动到某一阈值点(例如,从视口顶部10像素),之后它变得固定。

参考文档:https://developer.mozilla.org/zh-CN/docs/Learn/CSS/CSS_layout/%E5%AE%9A%E4%BD%8D

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/80188704