元素定位 position

157 阅读1分钟

元素定位 position(配合方位使用)

属性值:

  • static 默认值
  • realative 相对定位
  • absolute 绝对定位
  • fixed 固定定位
  • sticky 粘性定位

一、相对定位

  • 相对于自己原本的位置进行定位
  • 不会脱离文档流,即定位后,原来的位置会保留
  • z-index层级会提高,可以把标准文档流中的元素及浮动元素盖在下边
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .left {
            position: relative;
            left: -20px;
        }
        .right {
            position: relative;
            left: 20px;
        }
    </style>
</head>
<body>
    <h2>这是一个正常位置的标题</h2>
    <h2 class="left">这个标题相对于其正常位置向左移动了20px</h2>
    <h2 class="right">这个标题相对于其正常位置向右移动了20px</h2>
</body>
</html>
  • 运行结果:

image.png

二、绝对定位

  • 定位参考对象为有定位的父级元素,如父级元素都无定位,则参考浏览器窗口
  • 会脱离文档流,原来位置不占位
  • 子绝父相,子元素绝对定位,父元素相对定位
  • 层级提高,可以把标准文档流中的元素及浮动元素盖在下边

三、固定定位

  • 参考坐标为浏览器窗口
  • 会脱离文档流,不占位(移动端页面布局的header和footer要给body设置padding:他们的高度)
  • 多用于吸顶菜单和侧边导航,要设置层级z-index

粘性定位

-当元素在屏幕内,表现为relative;当元素在要滚出屏幕外时,表现为fixed