博客列表 >css样式和选择器的使用方法

css样式和选择器的使用方法

徐凤年
徐凤年原创
2021年12月27日 15:07:18467浏览

一、实例演示样式的来源

1.用户代理样式

  • 当 html 标签没有明确指定样式的时候,浏览器会默认生成样式;即用户代理样式,或着称之为浏览器默认样式 。

html 代码:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <a href="http://php.cn">祝php中文网越办越好</a>
  11. </body>
  12. </html>

浏览器生成用户代理样式:

  1. body {
  2. display: block;
  3. margin: 8px;
  4. }

2.用户自定义样式

用户自定义样式分为:

  • 行内样式
  • 文档样式
  • 外链样式 ####行内样式
  • <p style="color: red">php中文网</p>

文档样式

  1. <style>
  2. p {
  3. color: rgb(111, 0, 255);
  4. }
  5. </style>

外部样式

<link rel="stylesheet" href="sytle.css" />

二、实例演示基本选择器、上下文选择器

1.基本选择器

  • 标签选择器
  1. a {
  2. color: red;
  3. }
  • 2.属性选择器
  1. h2[title="hello"] {
  2. color: green;
  3. }
  4. h2.b {
  5. color: orange;
  6. }
  7. h2#a,
  8. h2.b {
  9. background-color: yellow;
  10. }
  • 3.群组选择器
  1. h2#a,
  2. h2.b {
  3. background-color: yellow;
  4. }
  • 4.通配选择器
  1. html body * {
  2. background-color: gray !important;
  3. }
  4. /* !important: 瞬间提权到100% */

2.上下文选择器

  1. <style>
  2. /* 1. 子元素f > */
  3. .list > li {
  4. border: 1px solid #000;
  5. }
  6. /* 2. 后代元素: 空格 */
  7. .list li {
  8. border: 1px solid #000;
  9. }
  10. /* 3. 相邻兄弟: + */
  11. .item.second + * {
  12. background-color: lightcyan;
  13. }
  14. /* 4. 所有兄弟: ~ */
  15. .item.second ~ * {
  16. background-color: yellow;
  17. }
  18. </style>

三、选择器的权重

id 权重>class 权重>标签权重
三个权重的位置, 从右到左 0(id).0(class).0(标签)

  1. 1位: 标签数量
  2. 2位: class数量
  3. 3位: id数量 */
  • css 将 id, class, tag 看成一个”三位整数”, id -> 百位, class -> 十位, tag -> 个位

  • id : 为什么不推荐用? 因为权重太高, 为了让你的代码具有弹性,尽可能用 class

  • 为什么不用权重最低的标签呢? 只是标签的数量太少了, 而 class 可以任何命名
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议