css-css执行的三种方式和css选择器
一.直接在标签中生效
1.1
<div style="color: red;">哪家强</div>
效果如下:
1.2 在head标签中添加style样式
<head><meta charset="UTF-8"><title>Title</title><style>.c1 {color: blue;}</style>
</head>
1.3 在指定的css文件中添加style样式
然后在指定的html页面引用
<head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="/static/css/commons.css">
</head>
二.css选择器
2.1 标签选择器
p {color: green; /* 选择所有 <p> 标签 */}
2.2 类选择器
带有特定类名的元素 (类名前加.)
/* 选择所有 class="highlight" 的元素 */
.highlight {background-color: yellow;
}/* 只选择class="info" 的 <p> 元素 */
p.info {font-size: 1.2em;
}
2.3 ID选择器
/* 选择id="logo" 的元素 ,ID前面加# */
#logo {width: 200px
}
2.4 属性选择器
根据元素的属性或者属性值选择元素
/* 选择所有带有disabled属性的元素*/
[disabled] {opacity: 0.5;
}/* 选择所有type="text"的标签*/
[type="text"] {border: 1px solid gray;
}/* 选择所有href属性以http开头的标签*/
[href^="http"] {color: green;
}
2.5 后代选择器
选择某个元素内部的后代元素 (用空格分隔)
/* 后代选择器*/
/* 选择<ul>内部的所有 <li>元素*/
ul li {list-style: square;
}/* 选择class="container" 的元素内部的所有 <p>元素*/
.container p {margin: 0;
}
2.6 子选择器
仅选择某个元素的直接子元素(用>分隔断)
/* 仅选择某个元素的直接子元素(用 > 分隔)*/
ul > li {border-bottom: 1px solid #eee;
}
2.7 相邻兄弟选择器
选择仅跟在某个元素后面的兄弟元素(用+分隔)
/*
相邻兄弟选择器
选择紧接在某个元素后的兄弟元素(用 + 分隔)
*/
h2 + p {font-weight: bold;
}
2.8 通用选择器
选择所有元素(用*表示)
* { margin: 0; padding: 0; } /* 清除所有元素的默认边距和内边距 */
2.9伪类选择器
根据元素的状态或位置选择元素 (用: 表示)
/*伪类选择器*/
/* 鼠标悬停时的链接样式*/
a:hover {text-decoration: underline;
}/*获取焦点时的输入框样式*/
input:focus {outline: 2px solid blue;
}
/* 奇数位置的 <li> */
li:nth-child(odd) {color: red;
}
2.10 伪元素选择器
选择元素的特定部分 (用::表示)
/*伪元素选择器
选择元素的特定部分
*/
p::first-line {font-weight: bold; /* 段落的第一行 */
}::before {content: "Hello"; /* 在元素之前添加内容 */
}