第一节 了解CSS | 青训营笔记

103 阅读3分钟

这是我参与「第四届青训营 」笔记创作活动的的第2天

CSS是什么

  • CSS指的是层叠样式表(Cascading Style Sheets)
  • CSS 是一种描述 HTML 文档样式的语言。
  • CSS 描述应该如何显示 HTML 元素。
  • 语法:

image.png

 选择器指向您需要设置样式的 HTML 元素
 声明块包含一条或多条用分号分隔的声明。

在界面中使用CSS

<!-- 外链 -->
<link rel="stylesheet" href="/assets/style.css">

<!-- 嵌入 -->
<style>
  li { margin: 0; list-style: none; }
  p { margin: 1em 0; }
</style>

<!-- 内联 -->
<p style="margin:1em 0">Example Content</p>

CSS是如何工作的

image.png

选择器Selector

找出页面中的元素,以便给他们设置样式

  • 选择方式:

    • 按照标签名、类名、id
    • 按照属性
    • 按照DOM树中的位置
  • 通配选择器

image.png

  • 标签选择器

image.png

  • id选择器

image.png

  • 类选择器

image.png

  • 属性选择器

image.png

image.png

image.png

  • 选择器组

image.png

伪类(pseudo-classes)

不基于标签和属性定位元素,用于定义元素的特殊状态

  • 状态伪类
/* 未访问的链接 */
a:link {
  color: #FF0000;
}

/* 已访问的链接 */
a:visited {
  color: #00FF00;
}

/* 鼠标悬停链接 */
a:hover {
  color: #FF00FF;
}

/* 已选择的链接 */
a:active {
  color: #0000FF;
}
  • 结构型伪类

image.png

组合(Combinators)

名称语法说明示例
直接组合AB满足A同时满足Binput:focus
后代组合A B选中B,如果它是A的子孙nav a
亲子组合A > B选中B,如果它是A的子元素section > p
兄弟选择器A ~ B选中B,如果它在A后且和A同级h2 ~ p
相邻选择器A + B选中B,如果它紧跟在A后面h2 + p

image.png

颜色

  • RGB
    • rgb(redgreenblue)

image.png

  • RGBA
    • 具有 alpha 通道的 RGB 颜色值的扩展。指定了颜色的不透明度
    • rgba(redgreenbluealpha)

image.png

  • HSL
    • hsla(huesaturationlightness)
    • 使用色相、饱和度和明度(HSL)来指定颜色
      • 色相(hue)是色轮上从 0 到 360 的度数。0 是红色,120 是绿色,240 是蓝色。
      • 饱和度(saturation)是一个百分比值,0% 表示灰色阴影,而 100% 是全色。
      • 亮度(lightness)也是百分比,0% 是黑色,50% 是既不明也不暗,100%是白色。

image.png

字体(font-family)

  • 在 CSS 中,有五个通用字体族:
    • 衬线字体(Serif)- 在每个字母的边缘都有一个小的笔触。它们营造出一种形式感和优雅感。
    • 无衬线字体(Sans-serif)- 字体线条简洁(没有小笔画)。它们营造出现代而简约的外观。
    • 等宽字体(Monospace)- 这里所有字母都有相同的固定宽度。它们创造出机械式的外观。
    • 草书字体(Cursive)- 模仿了人类的笔迹。
    • 幻想字体(Fantasy)- 是装饰性/俏皮的字体。

image.png

  • 在 CSS 中,使用 font-family 属性规定文本的字体

image.png

font-family使用建议
   - 字体列表最后写上通用字体族
   - 英文字体放在中文字体前面
  • 使用Web Fonts

image.png

  • font-size 字体大小
    • 关键字
      • small、medium、large
    • 长度
      • px、em
    • 百分数
      • 相对于父元素字体大小
<section>
  <h2>A web font example</h2>
  <p class="note">Notes: Web fonts ...</p>
  <p>With this in mind, let's build...</p>
  <p class="small">Notes: small</p>
  <p class="medium">Notes: medium</p>
  <p class="large">Notes: large</p>
</section>

<style>
  section {
    font-size: 20px;
    color: green;
  }

  section h2 {
    font-size: 2em;
    color: red;
  }

  section .note {
    font-size: 80%;
    color: orange;
  }
  
  section .small {
    font-size: small;
    color: pink;
  }
  section .medium {
    font-size: medium;
    color: pink;
  }
  section .large {
    font-size: large;
    color: pink;
  }
</style>

image.png

  • font-style
    • font-style 属性主要用于指定斜体文本
    • normal - 文字正常显示
    • italic - 文本以斜体显示
    • oblique - 文本为“倾斜”(倾斜与斜体非常相似,但支持较少)
  • font-weight
    • font-weight 属性指定字体的粗细

image.png

调试CSS

  • 右键点击页面,选择「检查」
  • 使用快捷键
    • Ctrl+Shift+I (Windows)
    • Cmd+Opt+I (Mac)