CSS入门 | 青训营笔记

139 阅读3分钟

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

什么是CSS?

Cascading Style Sheets,主要负责样式

构成

选择器{ 属性:属性值; }

选择器selector + { 多条声明 declaration } → 构成规则

在页面中如何使用

  • 外链

将css规则放在单独的文件中,并用 <link...> 标签引入html HTML文档中<head> <link rel="stylesheet" href="...url.css"> </head>

  • 嵌入

将样式规则直接嵌入html文档中 <head> <style> ...css规则... </style> </head>

  • 内联

HTML标签都自带style属性 内联样式不需要选择器,直接写在元素标签中即可 <开始 style="属性:属性值"> ... </结束>

❗ 内容与样式分离

CSS如何工作

image.png

如何选择样式的适用对象?

选择器

image.png
  • 通配选择器:用 * 匹配所有元素

<style> *.{ color:red; } </style>

  • 标签选择器:使用HTML中的标签

<style> h1{ color:red; } </style>

  • id选择器:给某些标签设置id后,可用 #id 形式设置样式,id值需唯一!

<h1 id="hello"> ... </h1> <style> #hello { color:red; } </style>

  • 类选择器

将某些元素设为一类 class ,然后用.类名为同一类型的元素设计样式,class 可出现多次

<tag1 class="hello">...</tag1> <tag2 class="hello">...</tag2> <style> .hello { color:red; } </style>

  • 属性选择器

通过元素的一些属性或属性值来选中这个元素,使用[属性]来进行选择

<input ... disabled />

<style> [disabled] { color:#999; } </style>

选择属性为特定值的元素,可使用 标签[属性:属性值]

<input ... type="password" />

<style> input[type="password"] { color:red; } </style>

匹配部分属性值:[属性 ^="..."]

匹配属性值的开头:[属性 $="..." ]

匹配结尾:

<p> <a href="#top">Back to top</a> </p>

<p> <a href="logo.jpg">See our logo</a> </p>

<style> a[href^="#"] { ... } a[href$=".jpg"] { ... } </style>

伪类 pseudo-classes

  • 状态性伪类

元素处于某种状态时,才会被选中

<a href="...">...</a>链接的不同状态:a:link {...} a:visited {...} a:hover {...} a:active {...}

输入框<input...>的输入状态 :focus {...}

  • 结构性伪类

根据DOM节点在DOM树中出现的位置,选择元素

标签:first-child {...} 标签:last-child {...}

组合 combinators

标签**.**属性值 {...}

image.png

选择器组

将一组选择器(标签、属性等)放在一起,用逗号隔开

CSS中的文本设计

颜色

RGB模型

rgb(xxx, xxx, xxx) 0~255

#xxxxxx 6位值,十六进制

HSL模型

更符合人的认知习惯:hue saturation lightness

hsl(0~360, 0~100%, 0~100%)

关键词直接指定颜色

直接写颜色的名字

alpha 透明度

十六进制:#.....数值

rgba(..., ..., ..., 小数值)

hsla(..., ...%, ...%, 小数值)

字体

font-family

可以指定多个字体,设备会从前到后选择可用的

记得最后要指定通用字体族:衬线、无衬线等 image.png

英文字体最好放在中文字体前面,设备会按照顺序显示可用的字体

{ font-family: xxx, xxxx, sans-serif; }

web fonts

将字体文件嵌入服务器中

<style> @font-face { font-family:"xxx"; src*url(http:...) format(...); } </style>

font-size

可用关键字、单位、百分比来表示

font-style

可以设为正常normal、斜体italic

font-weight

对于字重的设置,也要看字体本身是否支持

line-height

行高:两行文字基准线之间的距离

可以用单位,也可以用倍数值,如line-height: 45px; line-height: 1.6;

image.png

文本对齐 text-align

left, right, center, justify

字间距 spacing

letter-spacing 每个字母之间的间距

word-spacing 词间距

首行缩进 text-indent

文字修饰

none, underline, line-through, overline

white-space

如何让浏览器正常显示空格?

默认:<p> 中多个空格会被合并成一个空格展示

normal, nowrap, pre, pre-wrap, pre-line