css(层叠样式表)
-
css?
修饰html标签的,html标签相当于盖房子的框架(钢筋,水泥),css则是规定这些材料的使用方式并加上一些装饰品(比如房子的造型,房子里的花瓶,电视)。
-
css样式的添加方式
有三种,内联(行内)样式,内部样式表,外部样式表。其中的优先级为内联样式>内部样式表>外部样式表。
<html <head> <title></title> <!-- 外部样式表:引入外部的css文件,文件中写样式 --> <link rel="stylesheet" type="text/css" href="cs.css"> <!-- 内部样式表 --> <style type="text/css"> h2{ color: red; } </style> </head> <body> <h2>内部样式示例</h2> <h3 style="color:blue;">行内样式示例</h3> </body>
-
css选择器
- 选择器
<html>
<head>
<title></title>
<!-- 外部样式表:引入外部的css文件,文件中写样式 -->
<link rel="stylesheet" type="text/css" href="cs.css">
<!-- 内部样式表 -->
<style type="text/css">
/*tag(标签选择器)*/
p{
margin:0 auto;
}
/*类选择器(不唯一)*/
.p{
font-size: 14px;
}
/*id选择器(规范要求唯一)*/
#p{
color:blue;
}
/*属性选择器*/
i[class="i"]{
color:gray;
}
/*
嵌套选择器:
1.普通:父元素的子孙
2.>:父元素的儿子
3.~:父元素的兄弟
4.+:父元素的第一个兄弟
*/
div span{
color:pink;
}
div > a{
color:blue;
}
.i ~ i{
color:yellow;
}
.em + em{
color:green;
}
</style>
</head>
<body>
<div>
<span>aaa</span><br>
<span>aaa</span><br>
<span>aaa</span><br>
<a>aaa</a><br>
<a>aaa</a><br>
<a>aaa</a><br>
<i class="i">aaa</i><br>
<i>aaa</i><br>
<i>aaa</i><br>
<em class="em">aaa</em>
<em>bbb</em><br>
</div>
</body>
</html>
- 伪类
链接伪类:hover
,link
,active
,visited
,对应链接的几种状态,在该状态下改变元素的样式。
其他伪类:target
用来点击链接修改另一个元素的样式。focus是表单元素获取到焦点的样式。first-child
、last-child
是标签下的第一个和最后一个元素的样式(first-child前面不能有同级元素)。first-of-type
、last-of-type
是对多个相同类型元素的第一个和最后一个设置样式。nth-child(f(n))
,第f(n)个元素的样式(做一些特效),nth-child(odd)
,nth-child(even)
分别是奇数和偶数个元素的样式。
<html>
<head>
<title></title>
<style type="text/css">
/*鼠标悬停的样式*/
a:hover{
color:yellow;
}
/*点击时的样式*/
a:active{
color:pink;
}
/*点击过的样式*/
a:visited{
color: green;
}
/* 正常样式 */
a:link{
color:gray;
}
/*href为p的id的a标签点击改变p的样式*/
p:target{
border: 1px red solid;
}
/*div1下的第一个类型为p的元素的样式*/
.div1 div:first-of-type{
color:red;
}
</style>
</head>
<body>
<a href="#a">a标签</a>
<p id="a">p标签</a>
<div class="div1">
<a href="##">11</a><br>
<div>aaa</div>
<div href="####">22</div><br>
<a href="###">33</a>
</div>
</body>
</html>
-
伪元素
伪元素类似在页面上添加了一个新的行内元素,伪类则是对已有元素和已有元素的行为给于样式。
::first-letter
,::first-line
,::before
,::after
.<html> <head> <title></title> <style type="text/css"> /*p1的第一个字符的样式*/ .p1::first-letter{ font-size: 30px; color: red; float:left; } /*p2的第一行文字的样式。*/ .p2::first-line{ color:blue; background-image: url("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3878847766,3988120331&fm=200&gp=0.jpg"); } /*p1的前面加一个元素*/ .p1::before{ content: "哈哈哈哈哈哈"; background-color: blue; } /*p1的后面加一个元素(在所有边都有颜色且存在时,会出现2个三角形和两个矩形(应为字体有高度)*/ .dv::after{ content: "aa"; border-top: 10px red solid; border-left: 10px blue solid; border-right: 10px yellow solid; border-bottom: 10px green solid; } </style> </head> <body> <br> <p class="p1">床前明月光,疑似地上霜。</p> <p class="p2">床前明月光,疑似地上霜。举头望明月,低头思故乡。</p> <div class="dv">床前明月光,疑似地上霜。举头望明月,低头思故乡。</div> </body> </html>
-
选择器权重比
如果标签选择器权重比为1,类选择器、id选择器、行内的权重比则分别为10,100,1000。嵌套选择器的权重比则相加。权重比指的是相同标签的影响力,如果权重比越大,则影响力越大,小的权重比的标签的效果被大的覆盖。