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";    /* 在元素之前添加内容 */
}
相关推荐
x***r1511 分钟前
Notepad++ 8.6 安装教程:详细步骤+自定义安装路径(附注意事项)
linux·前端·javascript
Hilaku4 分钟前
为什么很多工作 5 年的前端,身价反而卡住了?🤷‍♂️
前端·javascript·面试
ai超级个体4 分钟前
前端下午茶:这 3 个网页特效建议收藏(送源码)
前端·three.js·threejs·网页设计·vibe coding·网页灵感·网页分享
维斯184 分钟前
VueFlow 图自适应容器尺寸教程
前端
helloweilei5 分钟前
next/dynamic和React.lazy的区别
前端·next.js
Aaron_Feng8 分钟前
一个小工具解决Swift Actor重入问题
前端
笨笨狗吞噬者9 分钟前
维护 uniapp 小程序端近一年,我想拉一个开发者交流群
前端·程序员·uni-app
前端炒粉15 分钟前
React 面试高频题
前端·react.js·面试
程序员陆业聪16 分钟前
让 Android 里的 AI 真正「干活」:Function Calling 工程实现全解
前端
mumuWorld18 分钟前
解决openclaw以及插件安装的报错
前端·ai编程