第二课 理解CSS之深入CSS 2 | 青训营笔记

105 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 7 天。

在了解盒模型后我们学习两种常见的布局结构。

块级VS行级

块级:

  • Block Level Box
  • 不能和其他盒子并列摆放
  • 适用所有的盒模型属性

行级:

  • Inline Level Box
  • 和其他行级盒子放在一行或拆开成多行
  • 盒模型中的width、height不适用

块级元素

  • 生成块级盒子
  • body、article、div、main、section、h1~h6、p、ul、li等
  • display:block

行级元素

  • 生成行级盒子
  • 内容分散在多个行盒(line box)中
  • span、em、strong、cite、code等
  • display:inline

display属性

  • block:块级盒子
  • inline:行级盒子
  • inline-block:本身是行级,可以放在行盒中;可以设置宽高;作为一 个整体不会被拆散成多行
  • none:排版时完全被忽略

常规流Normal Flow

  • 根元素、浮动和绝对定位的元素会脱离常规流
  • 其他元素都在常规流之内(in-flow)
  • 常规流中的盒子,在某种排版上下文在中参与布局

3.jpg

行级排版上下文

  • Inline Formatting Context (IFC)
  • 只包含行级盒子的容器会创建个IFC
  • IFC内的排版规则
    • 盒子在一行内水平摆放
    • 一行放不下时,换行显示
    • text-align决定一行内盒 子的水平对齐
    • vertical-align 决定个盒子在行内的垂直对齐
    • 避开浮动(float)元素*

块级排版上下文

  • Block Formatting Context (BFC)
  • 某些容器会创建一个BFC
    • 根元素
    • 浮动、绝对定位、inline-block
    • Flex子项和Grid子项
    • overflow值不是visible 的块盒
    • display: flow-root;

BFC内的排版规则

  • 盒子从上到下摆放
  • 垂直margin合并
  • BFC内盒子的margin不会与外面的合并
  • BFC不会和浮动元素重叠
<span>
  This is a text and
  <div>block</div>
  and other text.
</span>

<style>
  span {
    line-height: 3;
    border: 2px solid red;
    background: coral;
  }

  div {
    line-height: 1.5;
    background: lime;
  }
</style>

4.jpg

Flex Box是什么?

  • 一种新的排版上下文
  • 它可以控制子级盒子的:
    • 摆放的流向(→←↑↓)
    • 摆放顺序
    • 盒子宽度和高度
    • 水平和垂直方向的对齐
    • 是否允许折行
<div class="container">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
</div>
<style>
  .container {
    display: flex;
    border: 2px solid #966;
  }

  .a, .b, .c {
    text-align: center;
    padding: 1em;
  }

  .a {
    background: #fcc;
  }

  .b {
    background: #cfc;
  }

  .c {
    background: #ccf;
  }
</style>

3.jpg

flex-direction

4.jpg

主轴与侧轴

3.jpg

justify-content

4.jpg

align-items

3.jpg

align-self

4.jpg

order

3.jpg