css-css执行的三种方式和css选择器

一.直接在标签中生效

1.1

html 复制代码
<div style="color: red;">哪家强</div>

效果如下:

1.2 在head标签中添加style样式

html 复制代码
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
       .c1 {
            color: blue;
        }
    </style>
</head>

1.3 在指定的css文件中添加style样式

然后在指定的html页面引用

html 复制代码
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/css/commons.css">
</head>

二.css选择器

2.1 标签选择器

html 复制代码
p {
            color: green;  /* 选择所有 <p> 标签 */
  }

2.2 类选择器

带有特定类名的元素 (类名前加.)

html 复制代码
/* 选择所有 class="highlight" 的元素 */
.highlight {
    background-color: yellow;
}

/* 只选择class="info" 的 <p> 元素 */
p.info {
    font-size: 1.2em;
}

2.3 ID选择器

html 复制代码
/* 选择id="logo" 的元素 ,ID前面加# */
#logo {
    width: 200px
}

2.4 属性选择器

根据元素的属性或者属性值选择元素

html 复制代码
/* 选择所有带有disabled属性的元素*/
[disabled] {
    opacity: 0.5;
}

/* 选择所有type="text"的标签*/
[type="text"] {
    border: 1px solid gray;
}

/* 选择所有href属性以http开头的标签*/
[href^="http"] {
    color: green;
}

2.5 后代选择器

选择某个元素内部的后代元素 (用空格分隔)

html 复制代码
/* 后代选择器*/
/* 选择<ul>内部的所有 <li>元素*/
ul li {
    list-style: square;
}

/* 选择class="container" 的元素内部的所有 <p>元素*/
.container p {
    margin: 0;
}

2.6 子选择器

仅选择某个元素的直接子元素(用>分隔断)

html 复制代码
/* 仅选择某个元素的直接子元素(用 > 分隔)*/
ul > li {
    border-bottom: 1px solid #eee;
}

2.7 相邻兄弟选择器

选择仅跟在某个元素后面的兄弟元素(用+分隔)

html 复制代码
/*
相邻兄弟选择器
选择紧接在某个元素后的兄弟元素(用 + 分隔)
*/
h2 + p {
    font-weight: bold;
}

2.8 通用选择器

选择所有元素(用*表示)

html 复制代码
* { margin: 0; padding: 0; } /* 清除所有元素的默认边距和内边距 */

2.9伪类选择器

根据元素的状态或位置选择元素 (用: 表示)

html 复制代码
/*伪类选择器*/
/* 鼠标悬停时的链接样式*/
a:hover {
    text-decoration: underline;
}

/*获取焦点时的输入框样式*/
input:focus {
    outline: 2px solid blue;
}
/* 奇数位置的 <li> */
li:nth-child(odd) {
    color: red;
}

2.10 伪元素选择器

选择元素的特定部分 (用::表示)

html 复制代码
/*伪元素选择器
选择元素的特定部分
*/
p::first-line {
    font-weight: bold;    /* 段落的第一行 */
}

::before {
    content: "Hello";    /* 在元素之前添加内容 */
}
相关推荐
LaoZhangAI19 分钟前
Kiro vs Cursor:2025年AI编程IDE深度对比
前端·后端
止观止22 分钟前
CSS3 粘性定位解析:position sticky
前端·css·css3
爱编程的喵32 分钟前
深入理解JavaScript单例模式:从Storage封装到Modal弹窗的实战应用
前端·javascript
lemon_sjdk1 小时前
Java飞机大战小游戏(升级版)
java·前端·python
G等你下课1 小时前
如何用 useReducer + useContext 构建全局状态管理
前端·react.js
欧阳天羲1 小时前
AI 增强大前端数据加密与隐私保护:技术实现与合规遵
前端·人工智能·状态模式
慧一居士1 小时前
Axios 和Express 区别对比
前端
I'mxx1 小时前
【html常见页面布局】
前端·css·html
万少1 小时前
云测试提前定位和解决问题 萤火故事屋 上架流程
前端·harmonyos·客户端