13. CSS定位与伪类/伪元素

最近在学习CSS时,我重点研究了定位(position)属性和伪类/伪元素的使用,这两个概念对于页面布局和元素样式控制非常重要。下面我将结合具体代码示例,分享我的学习心得。

一、CSS定位(position)详解

定位是CSS中控制元素位置的重要属性,共有5种定位方式:

1. 静态定位(static) - 默认值

.box {
   
    position: static; /* 默认值,元素按正常文档流排列 */
}

2. 相对定位(relative) - 相对于自身定位

<div class="relative">div>
<style>
.relative {
     
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    top: 100px; /* 向下偏移100px */
    left: 0px;  /* 保持原位置 */
}
style>

特点

  • 不脱离文档流,原位置保留
  • 可以通过top/right/bottom/left调整位置
  • 层级(z-index)会提升
  • 常用于微调元素位置

3. 固定定位(fixed) - 相对于视口定位

<div class="fixed">div>
<style>
.fixed {
     
    width: 100px;
    height: 100px;
    background-color: rgb(7, 39, 4);
    position: fixed;
    top: 100px; /* 距离视口顶部100px */
}
style>

你可能感兴趣的:(前端学习,#,html+css,css,前端)