Skip to content

CSS 视觉与层叠

层叠上下文 · 伪元素 · 隐藏方式 · 三角形 · 正方形 · 文本溢出


1. 层叠上下文与 z-index

层叠顺序(从上到下):背景和边框 → 负 z-index → 块级盒 → 浮动盒 → 行内盒 → z-index:0 → 正 z-index

z-index 生效条件positionrelative/absolute/fixed/sticky

失效场景

  • 父元素 position: relative 时子元素 z-index 可能失效
  • 元素未设置 position 为非 static
  • 同时设置了 float

2. 伪元素与伪类

  • 伪类:hover:first-child:nth-child():not() — 改变元素状态
  • 伪元素::before::after::first-line — 插入额外内容
  • CSS3 双冒号 :: 区分伪类与伪元素

3. 隐藏元素的方式

方式占空间响应事件触发回流
visibility: hidden
display: none
opacity: 0
transform: scale(0)
height: 0 + 无边框

4. CSS 纯三角形

css
.triangle {
  width: 0; height: 0;
  border: 50px solid transparent;
  border-top: 50px solid pink;  /* 朝下的三角形 */
}

原理:border 由三角形组成,设宽高为 0 后只显示一侧。


5. 宽高自适应正方形

css
/* 方式一:vw */
.square { width: 10%; height: 10vw; }

/* 方式二:padding-top 百分比(相对父元素 width) */
.square { width: 20%; height: 0; padding-top: 20%; }

/* 方式三:伪元素 */
.square { width: 30%; overflow: hidden; }
.square::after { content: ''; display: block; margin-top: 100%; }

6. 画一条 0.5px 的线

css
/* transform 缩放 */
transform: scale(0.5, 0.5);

7. 文本溢出省略

css
/* 单行 */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

/* 多行 */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;