CSS定位相关知识点记录(position)

219 阅读3分钟

一、为什么需要定位

为了实现标准流和浮动无法快速实现或实现起来很困难的效果,需要使用定位

二、定位组成(定位模式 + 边偏移)

1.定位模式

  • 1.static静态定位
  • 2.relative相对定位
  • 3.absolute绝对定位
  • 4.fixed固定定位

2.边偏移

  • 边偏移就是定位的盒子移动到最终的位置,有top/bottom/left/right属性

三、定位模式

1.静态定位(static)

表示元素的默认定位方式,无定位

选择器{position:static}
  • 按照默认的定位方式进行定位,没有边偏移
  • 一般很少使用

2.相对定位(relative)

特点:

  • 相对于自己原来位置作为参照点移动的
  • 移动后原来位置仍然保留,后面的盒子依然遵循标准流
  • 典型应用是给绝对定位作为父布局限制绝对定位
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  div{
    width: 100px;
    height: 100px;
  }
  .box1{
    background-color: red;
    position: relative;
    top: 20px;
    left: 20px;
  }
  .box2{
    background-color: royalblue;
  }
</style>
<body>
  <div class="box1">

  </div>
  <div class="box2">

  </div>
</body>

3.绝对定位(absolute)

  • 绝对定位元素是相对于它父元素(祖先元素)来定位的

特点

  • 如果定位元素没有父元素或者父元素(祖先元素)没有定位属性,那就会按照浏览器文档定位
  • 如果父级(祖先)元素有定位属性,(相对、绝对、固定),则以最近一级的有定位祖先元素为参考点移动位置
  • 绝对定位会脱离标准流
<style>
  .father{
    width: 500px;
    height: 500px;
    position: relative;
    background-color: skyblue;
  }
  div{
    width: 100px;
    height: 100px;
  }
  .box1{
    background-color: red;
    position: absolute;
    bottom: 50px;
    right: 50px;
  }
</style>
<body>
    <div class="father">
      <div class="box1">
  
      </div>
    </div>
</body>

4.固定定位(fixed)

  • 以浏览器的可视窗口作为移动端移动(不随滚动条滚动、无父元素限制)
  • 脱离标准流,不再占有原来位置
<style>
  .father{
    width: 500px;
    height: 500px;
    background-color: skyblue;
  }
  .pofex{
    position: fixed;
    width: 50px;
    height: 50px;
    background-color: rebeccapurple;
    top: 30px;
  }
</style>
<body>
    <div class="father">
    <div class="pofex">

    </div>
</body>

5.粘性定位(sticky,类似于吸顶效果) 可以认为是相对定位和固定定位的混合体

  • 以浏览器的可视窗口准来移动元素
  • 不脱离标准流,占有原来的位置
  • 必须添加边偏移才生效(top、bottom、left、right)
  • 兼容性差,ie完全不支持
<style>
  body{
    height: 1500px;
  }
  .nav{
    width: 800px;
    height: 40px;
    background-color: skyblue;
    margin: 0 auto;
    position: sticky;
    top: 0px;
  }
</style>
<body>
    <div class="nav">
      
    </div>
</body>

特殊性

  • 行内元素添加绝对定位或固定定位后可以设置高度和宽度
  • 块级元素添加绝对定位或固定定位后,如果不设置宽高,默认大小是内容的大小