了解CSS|青训营笔记

了解CSS|青训营笔记

我的图图呢 1,085 2022-07-24

CSS

Cascading Style Sheets

用来定义页面元素样式

  • 设置字体和颜色
  • 设置位置和大小
  • 添加动画效果

例子:

h1 { // selector
    color: white; // property: value
    font-size: 14px; // declaration
}

在页面中使用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>

07D47FA6-EFEB-4D1C-8D0A-FF8BF59D18A0

选择器

作用:寻找页面中符合规则的元素,给他们设置相应样式。

选择器分为很多种:

  • 标签名、类名、id
  • 属性
  • DOM树中的位置
<style>
  <!-- 通配选择器 -->
  * { 
  	color: red;
  }
  <!-- 标签选择器 -->
  h1 { 
  	color: orange;
  }
  <!-- id 选择器,注意 id 唯一 -->
  #logo { 
  	width: 180px;
  }
  <!-- 类选择器 -->
  .done { 
  	color: gray;
  }
  <!-- 属性选择器,对所有 disable=true 的元素生效 -->
  [disabled] { 
  	background: #eee;
  }
  <!-- 限定属性值的选择器 -->
  input[type ="password"]{ 
  	color: red;
  }
  <!-- 属性以#开头的匹配原则,类似正则表达式 -->
  a[href^="#"] { 
    color: #f54767;
  }
</style>

还有一类特殊的选择器:伪类选择器

  • 不基于标签和属性寻找元素
  • 分为状态伪类结构性伪类
<style>
<!-- 状态伪类 -->
a:link {
  color: black;
}

a:visited {
  color: gray;
}

a:hover {
  color: orange;
}

a:active {
  color: red;
}

:focus {
  outline: 2px solid orange;
}

<!-- 结构性伪类 -->
li {
  list-style-position: inside;
  border-bottom: 1px solid;
  padding: 0.5em
}

li:first-child {
  color: coral
}

li:last-child {
  border-bottom: none;
}
</style>

选择器组合语法

507CCF93-9AE4-4E33-A291-45177C4B9750

<!-- p是article的子元素,可以是孙子 -->
  article p {
    color: black;
  }
<!-- article的直接子元素p会被选中 -->
  article > p {
    color: blue;
  }
<!-- h2后面的p元素会被选中 -->
  h2 + p {
    color: red; 
  }
<!-- 选择器组 -->
<!-- 对每个逗号的片段处理方式都一样 -->
body, h1, h2, h3, h4, h5, h6, ul, ol, li {
  margin: 0;
  padding: 0;
}
 
[type="checkbox"], [type="radio"] {
  box-sizing: border-box;
  padding: 0;
}

特殊声明

颜色

color有多种颜色模型

  • rgb
  • hsl (色相,饱和度,亮度)
  • rgba
  • hsla

字体

font-family 用来显示字体

  • 设置很多个,会按照从前到后的顺序匹配
  • 字体列表最终要加上通用字体族
  • 英文字体放在中文字体前面

可以使用@font-face来引入字体

font-size 用来定义字体大小

  • px 绝对大小
  • em 相对于父级字体大小
  • 百分比 相对于父级字体大小

font-weight 设置字重

line-height 表示两行文字基准线之间的距离

font 总属性 定义为: style weight size/height family

h1 {
<!-- 斜体 粗细 大小/行高 字体族  -->
  font: bold 14px/1.7 Helvetica, sans-serif;
}
 
p {
  font: 14px serif;
}

空白符

可以通过white-space属性控制空白格的展示规则。
html会默认将多个空格合并成一个。

  • normal 默认动作
  • nowrap 强制不换行,展示所有空格
  • pre 全部展示(换行和空格)
  • pre-wrap 会进行自动换行,保留空格
  • pre-line 合并空格,保留换行