CSS

286 阅读1分钟

position

box-sizing

CSS 基础框盒模型介绍

position

CSS position属性用于指定一个元素在文档中的定位方式。top,right,bottom 和 left 属性则决定了该元素的最终位置。

取值是否脱离文档流是否保留元素原位置相对什么位置进行偏移应用备注
static不偏移默认值。位置和布局不变。(正常布局,元素在文档流中当前的布局位置)此时 top, right, bottom, leftz-index 属性无效。
relative元素原位置原位置保留。相对元素未添加定位时的位置偏移。position:relative 对 table-*-group, table-row, table-column, table-cell, table-caption 元素无效。
absolute最近的非 static 定位祖先元素(当这样的祖先元素不存在时,则相对于ICB(inital container block, 初始包含块))不保留原位置,做偏移绝对定位的元素可以设置外边距(margins),且不会与其他边距合并。
fixed屏幕视口(viewport)屏幕滚动,元素相对于 viewport 视口仍处于同一位置fixed 属性会创建新的层叠上下文。当元素祖先的 transform, perspectivefilter 属性非 none 时,容器由视口改为该祖先。
sticky*最近滚动祖先(nearest scrolling ancestor)*和 containing block (最近块级祖先 nearest block-level ancestor)元素在跨越特定阈值前为相对定位,之后为固定定位(常用于定位字母列表的头部元素)

relative(相对定位)

#two {
  position: relative;
  top: 20px;
  left: 20px;
  background: blue;
}

absolute(绝对定位)

#three {
   position: absolute;
   top: 20px;
   left: 20px;
}

fixed(固定定位)

#one {
  position: fixed;
  top: 80px;
  left: 10px;
}

sticky(粘性定位)

#one { position: sticky; top: 10px; }