← 返回题库
前端核心·真题演练

前端真题 130 题 · CSS 基础

盒模型、CSS 选择器、div 居中、浮动等 20-23 题。

CSS盒模型选择器居中浮动

二、CSS 基础

20. 盒子模型

CSS 中每个元素是一个矩形"盒子",由四部分组成:content(内容)→ padding(内边距)→ border(边框)→ margin(外边距)

两种标准

  1. W3C 标准盒模型(content-box,默认)width/height = 内容的宽高,实际占位还要加 padding+border。
  2. IE 盒模型(border-box)width/height 已包含 padding+border(content 被压缩)。box-sizing: border-box 即是。
/* 对比:同样设置 width:100px; padding:10px; border:5px */
.content-box { box-sizing: content-box; } /* 实际占用 100+20+10=130px */
.border-box  { box-sizing: border-box;  } /* 实际占用恰好 100px */

margin 特性

  • 垂直方向的相邻 margin 会合并(collapse)(取较大值);
  • margin 可用负值(让元素位移/拉宽);
  • margin: auto 在块级元素 + 定宽时水平居中(flex 下子项 margin:auto 更强大)。

考察点

  • 能画出盒子结构并说明 width 指哪一层;
  • 推荐全局 * { box-sizing: border-box; }(或 border-box 于布局组件),并解释原因:padding/border 不再"撑破"设定宽度,栅格/百分比布局更好算;
  • 说出 margin 塌陷及解法(BFC、padding、border、overflow)。

21. CSS 选择器

按类别记忆:

  1. 基础选择器:通配 *、标签 div、类 .cls、ID #id
  2. 组合器(关系选择器)
    • 后代 div p(空格,任意层级)
    • 子代 div > p(直接子级)
    • 相邻兄弟 h1 + p(紧挨的后面一个)
    • 通用兄弟 h1 ~ p(后面所有兄弟)
  3. 属性选择器[attr][attr=v][attr^=v][attr$=v][attr*=v]
  4. 伪类(状态/位置):hover:focus:active:visited:link:checked:disabled:not():nth-child(n):first-child:last-child:first-of-type:empty:root:is()/:where()/:has()
  5. 伪元素(生成内容/局部)::before::after::first-line::first-letter::placeholder::selection

易错与进阶

  • :nth-child:nth-of-type 区别:前者按所有子元素序号,后者按同类标签序号;
  • 伪元素是"元素"(可设 content、样式),伪类是"状态";
  • :has() 是父选择器(div:has(> img) 选择直接包含 img 的 div),2023 后主流浏览器已支持;
  • 选择器越复杂匹配越慢,优先类选择器;* 慎用。

22. div 居中

水平 + 垂直居中的主流方案及适用场景:

/* 1) flex(最通用,推荐) */
.parent { display: flex; align-items: center; justify-content: center; }

/* 2) grid */
.parent { display: grid; place-items: center; }

/* 3) 绝对定位 + translate(宽高未知可用) */
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
/* 前提:祖先需是定位容器;也可 top/left/right/bottom:0 + margin:auto(需定宽高)*/

/* 4) 绝对定位 + margin:auto(定宽高) */
.child { position: absolute; inset: 0; margin: auto; width: 100px; height: 100px; }

/* 5) table-cell(老方案) */
.parent { display: table-cell; text-align: center; vertical-align: middle; }

考察点

  • 区分"居中元素宽高是否已知";
  • flex/grid 是现代首选;
  • transform 方案不受定宽高限制且动画性能好,但注意会创建层叠上下文/影响 fixed;
  • 行内元素居中:text-align:center + line-height

23. 浮动(float)

float: left/right 让元素脱离文档流向左/右靠,后续内容环绕。核心特性与问题:

  1. 脱离文档流但保留行框:元素浮动后不再占普通流位置,但文字/行内盒子会"环绕"它,产生文字环绕报纸布局;
  2. 高度塌陷:父容器不包含浮动子元素 → 父高度为 0;
  3. 清除浮动
    • 父容器触发 BFC:overflow:hidden / display:flow-root
    • clearclear:both 加在兄弟/占位元素上;经典"clearfix":
.clearfix::after { content: ''; display: block; clear: both; }
  1. 副作用:浮动元素会影响后续元素排列(被遮/环绕)。

现代视角:float 最初为文字环绕设计;布局已由 flex/grid 取代。面试考 float 是为检验对"脱离文档流"的理解是否透彻——能准确讲清脱离文档流与 absolute 脱离文档流的区别(float 部分脱离、还参与行框;absolute 完全脱离)。