前言

【重学前端】系列推荐: HTML 篇

CSS 是一种描述 HTML 文档样式的语言。
CSS 是前端需要掌握的最基本的技能,决定了一个程序员的下限。

正文

盒模型

CSS 盒模型本质上是一个盒子,它包括:边距、边框、内容。

CSS 盒模型包括:IE 盒模型(怪异盒模型)W3C 盒模型(标准盒模型)

标准盒模型宽度 = width + margin(left & right) + padding(left & right) + border(left & right)

怪异盒模型宽度 = width + margin(left & right)
width 已经包含了 padding 和 border 的值

选择器

  • id 选择器 (#myid)
  • 类选择器 (.myclass)
  • 属性选择器 (a[href] {color:red;})
  • 伪类选择器 (a:hover, li:nth-child)
  • 标签选择器 (div, h1,p)
  • 相邻选择器 (h1 + p)
  • 子选择器 (ul > li)
  • 后代选择器 (li a)
  • 通配符选择器 (*)

优先级:

  • !important
  • 内联样式
  • id 选择器
  • 类选择器 / 属性选择器 / 伪类选择器
  • 元素选择器 / 伪元素选择器
  • 关系选择器 / 通配符选择器

!important > 行内样式 > id 选择器 > 类选择器 > 标签 > 通配符 > 继承 > 浏览器默认属性

BFC

BFC: Block Formatting Context, 块级格式化上下文。BFC 是一个独立的渲染区域,规定了内部的 box 如何布局,并且这个区域的子元素不会影响到外面的元素,计算 BFC 高度的时候,浮动元素也参与计算。

BFC 的布局规则

  • 内部的 box 会在垂直方向一个接一个排列
  • box 垂直方向的距离由 margin 决定,属于同一个 BFC 的两个相邻 box 的 margin 会发生重叠
  • BFC 的区域不会与 float box 发生重叠
  • BFC 是一个独立容器,里面元素不会影响到外面元素
  • 计算 BFC 的高度的时候,浮动元素也参与计算高度
  • 元素的类型和 display 属性决定了这个 box 的类型,不同类型的 box 会参与不同的 formatting context

如何创建 BFC

  • 根元素,即 HTML 元素
  • float 的值不为 none
  • position 为 absolute 或者 fixed
  • display 的值为 inline-block
  • overflow 的值不为 visible

BFC 使用场景

  • 去除边距重叠
  • 清除浮动

flex

flex 是 flexible box 的缩写,意为“弹性布局”。通过指定容器的 display 属性为 flex 即可。

容器属性:

  • flex-direction: row | row-reverse | column | column-reverse;
  • flex-wrap: nowrap | wrap | wrap-reverse;
  • justify-content: flex-start | flex-end | center | space-between | space-around;
  • align-items: flex-start | flex-end | center | baseline | stretch;
  • align-content: flex-start | flex-end | center | space-between | space-around | stretch;

元素属性:

  • order 属性:定义项目的排列顺序,顺序越小,排列越靠前,默认为 0
  • flex-grow 属性:定义项目的放大比例,即使存在空间,也不会放大
  • flex-shrink 属性:定义了项目的缩小比例,当空间不足的情况下会等比例的缩小,如果定义个 item 的 flow-shrink 为 0,则为不缩小
  • flex-basis 属性:定义了在分配多余的空间,项目占据的主轴空间
  • flex: 是 flex-grow 和 flex-shrink、flex-basis 的简写,默认值为 0 1 auto
  • align-self: 允许单个项目与其他项目不一样的对齐方式,可以覆盖
    align-items: 默认属性为 auto,表示继承父元素的 align-items

媒体查询

.example {
  padding: 20px;
  color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
  .example {
    background: red;
  }
}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
  .example {
    background: green;
  }
}

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
  .example {
    background: blue;
  }
}

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
  .example {
    background: orange;
  }
}

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
  .example {
    background: pink;
  }
}

移动端适配

预处理 less | sass

动画