理解CSS | 青训营笔记

93 阅读2分钟

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

CSS

概念

  • 用来定义页面元素的样式

    • 字体 颜色

    • 位置 大小

    • 动画效果

使用方法

  • 外链(推荐)

  • 嵌入

  • 内联

工作原理

image-20230116111627466

选择器

通配选择器(选择所有)

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

标签选择器

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

id选择器#

  • id唯一
<h1 id="one"></h1>
<style>
    #id{
        color:red;
    }
</style>

类选择器.

  • 可重复
<h1 class="one"></h1>
<style>
    .one{
        color:red;
    }
</style>

属性选择器[]

<p>
  <label>密码:</label>
  <input type="password" value="123456" />
</p>

<p><a href="#top">回到顶部</a></p>
<p><a href="a.jpg">查看图片</a></p>

<style>
   /*特定属性的值*/
  input[type="password"] {
    border-color: red;
    color: red;
  }

    a[href^="#"] {
    color: #f54767;
  }
 
  a[href$=".jpg"] {
    color: deepskyblue;
  }
</style>    
  • ^=" ":以…开头会被选中
  • $=" ":以…结尾会被选中

状态伪类

  • 当元素处于特定状态下,才会被选中
<a href="http://example.com">
  example.com
</a>

<label>
  用户名:
  <input type="text">
</label>

<style>
    /*默认状态*/
	a:link {
  	color: black;
	}
	/*被访问过状态*/
	a:visited {
  	color: gray;
	}
	/*鼠标悬停状态*/
	a:hover {
  	color: orange;
	}
	/*鼠标点击后状态*/
	a:active {
  	color: red;
	}
	/*输入状态*/
	a:focus {
 	 outline: 2px solid orange;
	}
</style>

结构伪类

  • DOM元素在DOM树中的位置
<ol>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
</ol>

<style>
li {
  border-bottom: 1px solid;
}

li:first-child {
  color: red;
}

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

组合

直接组合AB

  • 满足A同时满足B。input: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

选择器组

  • 选择多个标签,用逗号隔开

颜色

  • RGB#00(red)00(green)00(blue)
  • HSL H(色相)S(饱和度)L(亮度)

透明度

  • 0(透明)-1(不透明)
  • RGBA#00 00 00 00(透明度)
  • HSLA

字体 font-family

  • Serif 衬线体:Georgia、宋体
  • Sans-Serif 无衬线体:Arial、Helvetica、黑体、微软雅黑
  • Cursive 手写体:Caflish Script、楷体
  • Fantasy:Comic Sans MS、Papyrus
  • Monospace 等宽字体:Consolas、Courier、中文字体

使用建议

  1. 字体列表最后标明通用字体族
  2. 英文字体放在中文字体前面

字体大小font-size

  • 关键字:small、medium、large
  • 长度:px、em(1em=16px)
  • 百分数:相对于父元素字体大小
<section>
  <h2>A</h2>
  <p class="note">Notes</p>
  <p>let's go</p>
</section>

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

  section h2 {
    font-size: 2em;
  }

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

字重font-weight

  • 100-900
    • 400:normal
    • 700:bold

行高line-height

  • line-height:a;实际行高:20px*a

文字对齐text-align

  • left、center、right、justify

文字间隙space

  • letter-spacing:字母间隙
  • word-spacing:单词间隙

文字缩进text-indent

文字修饰text-decoration

  • none、underline(下划线)、line-through(删除线)、overline(上划线)

white-space

  • normal、nowrap(强制不换行)、pre(保留所有)
  • pre-wrap(保留空格。若一行显示不下,则自动换行)
  • pre-line(合并空格,保留换行)

调试C SS

右击点击页面选择[检查]

个人总结

伪类和组合选择器第一次了解。

还有一些细节需要注意,例如在选择字体时,英文在前,中文在后,最后最好标明通用字体族。