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";    /* 在元素之前添加内容 */
}
相关推荐
江公望3 小时前
VUE3中,reactive()和ref()的区别10分钟讲清楚
前端·javascript·vue.js
攀登的牵牛花3 小时前
前端向架构突围系列 - 框架设计(二):糟糕的代码有哪些特点?
前端·架构
EndingCoder3 小时前
函数基础:参数和返回类型
linux·前端·ubuntu·typescript
码客前端3 小时前
理解 Flex 布局中的 flex:1 与 min-width: 0 问题
前端·css·css3
Komorebi゛3 小时前
【CSS】圆锥渐变流光效果边框样式实现
前端·css
工藤学编程3 小时前
零基础学AI大模型之CoT思维链和ReAct推理行动
前端·人工智能·react.js
徐同保3 小时前
上传文件,在前端用 pdf.js 提取 上传的pdf文件中的图片
前端·javascript·pdf
怕浪猫3 小时前
React从入门到出门第四章 组件通讯与全局状态管理
前端·javascript·react.js
欧阳天风3 小时前
用setTimeout代替setInterval
开发语言·前端·javascript
EndingCoder3 小时前
箭头函数和 this 绑定
linux·前端·javascript·typescript