好的,下面是对CSS相关面试题的详细解答:
1. **什么是BFC(Block Formatting Context)?**
- BFC(Block Formatting Context),即块级格式化上下文,是Web页面的可视CSS渲染的一部分,是布局过程中生成块级盒子的区域,也是浮动元素与其他元素的交互限定区域。
- BFC主要有以下特点:
- 内部的Box会在垂直方向一个接一个地放置。
- Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠。
- 每个元素的margin box的左边,与包含块border box的左边相接触(对于从左往右的格式化,否则相右边)。
- BFC的区域不会与float box重叠。
- BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
- 触发BFC的条件:
- float属性不为none(即左浮动、右浮动)
- position为absolute或fixed
- display为inline-block、table-cell、table-caption
- overflow不为visible
2. **什么是盒模型?**
- CSS中的盒模型描述了元素所占用的空间。每个HTML元素都可以被看作一个盒子,这个盒子由以下部分组成:
- Content area: 元素的实际内容
- Padding area: 元素内容和边框之间的空白区域
- Border area: 包围元素内容和内边距的边框
- Margin area: 元素外部的空白区域
- 盒模型有两种:
- 标准盒模型(content-box): width和height只包括内容区域,不包括边框和内边距。
- IE盒模型(border-box): width和height包括内容区域、内边距和边框。
3. **未知高度元素垂直居中的几种方案?**
- 1. 使用transform属性:
```css
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
```
- 2. 使用flexbox布局:
```css
.parent {
display: flex;
align-items: center;
}
```
- 3. 使用table-cell布局:
```css
.parent {
display: table-cell;
vertical-align: middle;
}
```
- 4. 使用Grid布局:
```css
.parent {
display: grid;
align-items: center;
}
```
4. **CSS3中有哪些新特性?**
- Selectors(新选择器): attribute selectors、child and sibling combinators、pseudo-classes、pseudo-elements
- Box Model: box-sizing、 border-radius、box-shadow
- Backgrounds and Borders: multiple backgrounds、background-size、border-image
- Text Effects: text-shadow、word-wrap
- 2D/3D Transformations: rotate、scale、translate、skew
- Transitions: transition-property、transition-duration、transition-timing-function、transition-delay
- Animations: @keyframes rule、animation properties
- Multi-column Layout: column-count、column-gap、column-rule
- User Interface: resize、outline-offset、box-sizing、nav-index
5. **什么是CSS预处理器/后处理器?为什么要使用它们?**
- CSS预处理器(如Sass、Less、Stylus)是一种特殊的编程语言,它能够提供更sophiscated的功能和特性,如变量、混合(mixin)、函数等,最终转换为标准的CSS。
- CSS后处理器(如PostCSS)则是在CSS文件完成编写后,通过各种插件对CSS进行处理,改变CSS的语法规则,实现更多功能。
- 使用它们的主要原因:
- 提高CSS的可维护性和可拓展性
- 增加代码的模块化和组件化
- 简化CSS的书写,提高开发效率
- 提供更多的函数和工具,拓展CSS的功能
6. **为什么会出现margin重叠的问题?怎么解决?**
- 产生margin重叠的原因:
- 相邻兄弟元素的margin-top和margin-bottom会发生重叠
- 空的块级元素的margin-top和margin-bottom会发生重叠
- 浮动元素和普通文档流元素的margin-top和margin-bottom也会发生重叠
- 绝对定位元素和浮动元素的margin不会和其他元素的margin发生重叠
- 解决方案:
- 给父元素设置overflow: auto或hidden
- 给父元素设置padding-top/padding-bottom
- 给父元素设置border
- 给父元素设置和子元素相同的background-color
- 触发BFC(Block Formatting Context)
7. **flex布局的相关知识点**
- 容器属性:
- `flex-direction`: 决定主轴的方向(row、row-reverse、column、column-reverse)
- `flex-wrap`: 决定是否换行(nowrap、wrap、wrap-reverse)
- `flex-flow`: `flex-direction`和`flex-wrap`的简写
- `justify-content`: 决定主轴上子元素的对齐方式
- `align-items`: 决定交叉轴上子元素的对齐方式
- `align-content`: 多根轴线的对齐方式
- 项目属性:
- `order`: 定义项目的排列顺序
- `flex-grow`: 定义项目的放大比例
- `flex-shrink`: 定义项目的缩小比例
- `flex-basis`: 定义在分配多余空间之前,项目占据的主轴空间
- `flex`: `flex-grow`, `flex-shrink` 和 `flex-basis`的简写
- `align-self`: 允许单个项目有与其他项目不一样的对齐方式