选择器

标签选择器

<h1>标题</h1>

h1 {
  color: blue;
}

类选择器

<div class="header">
  <h1>标题</h1>
</div>

.header {
  color: blue;
}

ID选择器

<div id="header">
  <h1>标题</h1>
</div>

#header {
  color: blue;
}

组合选择器

/* 会同时选中所有 h1 和 .special */
<h1 class="title">标题1</h1>
<h1 class="title">标题2</h1>
<div class="special"></div>

h1, .special {
  color: blue;
}

属性选择器

li[class] {/* 选择所有有 class 属性的 li 标签 */}

li[class="a"] {/* 选择 class 属性值为 "a" 的 li 标签 */}

li[class~="a"] {/* 选择 class 属性值包含 "a类" 的 li 标签 */}

li[class|="zh"] {/* 选择 class 属性值以 "zh" 开头并且后面跟随一个连字符'-'的 li 标签 */}

li[class^="a"] {/* 选择 class 属性值以 "a" 开头的 li 标签 */}

li[class$="a"]  {/* 选择 class 属性值以 "a" 结尾的 li 标签 */}

li[class*="a"] {/* 选择 class 属性值包含 "a" 的 li 标签 */}

关系选择器

article p {/* 选择 article 下的所有 p 元素 */}
article > p {/* 选择 article 下的直接子元素 p 元素, 不会选中嵌套的 p 元素 */}
h1 + p {
   /* 选择 h1 元素的下一个兄弟元素 p 元素, 会选中紧接着 h1 的 p 元素 */
   <article>
      <h1>A heading</h1>
      <p>
         Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion
         daikon amaranth tatsoi tomatillo melon azuki bean garlic.
      </p>

      <p>
         Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette
         tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato.
         Dandelion cucumber earthnut pea peanut soko zucchini.
      </p>
   </article>
}


article ~ p {
   /* 选择 article 元素之后的所有兄弟元素 p 元素, 会选中下方所有的 p 元素 */
   <article>
      <h1>A heading</h1>
      <p>I am a paragraph.</p>
      <div>I am a div</div>
      <p>I am another paragraph.</p>
   </article>
}

伪类和伪元素

常用伪类

article p:first-child { /* 选择 article 下第一个 p 元素 */}

article p:last-child { /* 选择 article 下最后一个 p 元素 */}

article p:nth-child(2) { /* 选择 article 下第二个 p 元素 */}

伪元素

article p:first-child::first-line {/* 选择 article 下的第一个 p 元素的第一行 */}
p::first-line {/* 选择 p 元素的第一行 */}
p::first-letter { /* 选择 p 元素的第一个字符 */
   font-size: 200%;
   color: red;
}
p::before {
   content: "前缀"; /* 在 p 元素前插入内容 */
}
p::after { /* 在 p 元素后插入内容 */
   content: "后缀";
}

盒模型

用display属性来控制盒子的显示类型。

block

  • 盒子会产生换行。
  • width 和 height 属性可以发挥作用。
  • 内边距、外边距和边框会将其他元素从当前盒子周围“推开”。
  • 如果未指定 width,方框将沿行向扩展,以填充其容器中的可用空间。在大多数情况下,盒子会变得与其- 容器一样宽,占据可用空间的 100%。
  • 某些 HTML 元素,如 <h1> 和 <p>,默认使用 block 作为外部显示类型。

inline

  • 盒子不会产生换行。
  • width 和 height 属性将不起作用。
  • 垂直方向的内边距、外边距以及边框会被应用但是不会把其他处于 inline 状态的盒子推开。
  • 水平方向的内边距、外边距以及边框会被应用且会把其他处于 inline 状态的盒子推开。

标准盒模型

  • padding 和 border 宽度不参与 width 和 height 计算。
  • width 和 height 只计算内容区域的宽度和高度。
.box {
  box-sizing: content-box; /* 默认值 */
}

替代盒模型

  • padding 和 border 宽度参与 width 和 height 计算。
.box {
  box-sizing: border-box;
}