📍 第七章:定位与层级

掌握元素定位和层叠上下文

7.1 position 属性详解

position 属性用于控制元素在页面中的位置。

static(默认)

元素按照正常的文档流排列,不受 top, right, bottom, left 的影响。

relative(相对定位)

元素相对于其正常位置进行定位,不会脱离文档流。

absolute(绝对定位)

元素相对于最近的已定位祖先元素进行定位,会脱离文档流。

fixed(固定定位)

元素相对于视口进行定位,不会随页面滚动而移动。

sticky(粘性定位)

元素在滚动到一定位置时会固定,结合了 relative 和 fixed 的特性。

定位示例

static
relative
absolute
sticky
.static {
    position: static;
}

.relative {
    position: relative;
    top: 20px;
    left: 20px;
}

.absolute {
    position: absolute;
    top: 50px;
    right: 50px;
}

.sticky {
    position: sticky;
    top: 0;
}

7.2 层叠上下文与 z-index

z-index

z-index 属性用于控制元素的堆叠顺序,值越大,元素越在上面。

.element1 {
    position: absolute;
    z-index: 1;
}

.element2 {
    position: absolute;
    z-index: 2; /* 在上面 */
}
⚠️ z-index 陷阱:z-index 只对已定位的元素(position 不是 static)有效。如果元素不在同一个层叠上下文中,z-index 的值可能不会按预期工作。

层叠上下文的创建

7.3 变换 (transform)

transform 示例

Hover me
.transform-item {
    transition: transform 0.3s ease;
}

.transform-item:hover {
    transform: scale(1.2) rotate(10deg);
}

常用 transform 函数

.transforms {
    /* 位移 */
    transform: translate(10px, 20px);
    transform: translateX(10px);
    transform: translateY(20px);
    
    /* 缩放 */
    transform: scale(1.2);
    transform: scaleX(1.5);
    transform: scaleY(0.8);
    
    /* 旋转 */
    transform: rotate(45deg);
    
    /* 倾斜 */
    transform: skew(10deg, 5deg);
    transform: skewX(10deg);
    transform: skewY(5deg);
    
    /* 组合变换 */
    transform: translate(10px, 10px) rotate(45deg) scale(1.2);
}

3D 变换

.perspective {
    perspective: 1000px;
}

.transform-3d {
    transform: rotate3d(1, 1, 0, 45deg);
    transform-style: preserve-3d;
}

实战案例

固定导航栏

.navbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    z-index: 1000;
}

.content {
    margin-top: 60px; /* 为固定导航栏留出空间 */
}

模态框

.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 30px;
    border-radius: 8px;
    max-width: 500px;
    width: 90%;
}

工具提示

.tooltip {
    position: relative;
    cursor: help;
}

.tooltip::after {
    content: "提示文本";
    position: absolute;
    bottom: 125%;
    left: 50%;
    transform: translateX(-50%);
    background: #333;
    color: white;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 14px;
    opacity: 0;
    transition: opacity 0.3s;
    pointer-events: none;
}

.tooltip:hover::after {
    opacity: 1;
}

动手练习

练习 1:定位实践

  1. 创建一个包含多个元素的容器
  2. 分别对不同元素应用 static, relative, absolute, fixed, sticky 定位
  3. 观察元素的位置变化

练习 2:z-index 测试

  1. 创建多个重叠的元素
  2. 设置不同的 z-index 值
  3. 观察元素的堆叠顺序
  4. 创建不同的层叠上下文,测试 z-index 的行为

练习 3:变换效果

  1. 创建一个卡片元素
  2. 为卡片添加 hover 效果,使用 transform 实现缩放和旋转
  3. 添加过渡效果,使变换更平滑
  4. 尝试 3D 变换效果