文章目录
什么是css
cascading style sheet 层叠级联样式表
css:w3c表现用于美化网页
css的优势:
- 内容和表现分离
- 网页结构变现统一,可以实现复用
- 样式十分丰富
- 建议使用独立于html的css文件
- 利于SEO,容易被搜索引擎收录
<!--规范 style里可以编写css代码,每一个声明最好使用分号结尾
语法:
选择器{
声明1;
声明2;
声明3;
}
-->
<style>
h1{
color: red;
}
</style>
<h1>标题1 </h1>
css的三种导入方式
样式遵循就近原则,谁离h1最近使用谁
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--内部样式-->
<style>
h1{
color: green;;
}
</style>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--优先级 :就近原则-->
<!--行内样式:在标签元素中,编写一个style属性,编写样式即可-->
<h1 style="color: red"></h1>
</body>
</html>
/*外部样式*/
h1{
color: yellow;;
}
外部样式的两种写法:
- 链接式:
<!--外部样式-->
<link rel="stylesheet" href="css/style.css">
- 导入式
@import是css2.1新增的,css3中不常用
<!--导入式-->
<style>
@import url("css/style.css");
</style>
选择器
作用:选择页面上的某一个或者某一类元素
基本选择器
- 标签选择器
- 类选择器 class
- id选择器
标签选择器
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
<!--标签选择器会选择到页面上所有的这个标签-->
h1{
color: #6660ff;
background: aqua;
border-radius: 24px;
}
p{
font-size: 40px;
}
</style>
</head>
<body>
<h1>韩</h1>
<h1>明</h1>
<p>明</p>
</body>
类选择器
好处:多个标签可以归类同一个class下,可以复用
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*类选择器的格式 .class的名称{}*/
.han{
color: #6660ff;
}
.ming{
color: red;
}
</style>
</head>
<body>
<h1 class="han">标题1</h1>
<h1 class="ming">标题2</h1>
<h1 class="han">标题3</h1>
<p class="han">p标签</p>
</body>
id选择器
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*id选择器 id必须保证全局唯一
使用#id名称{}
不遵循就近原则,固定的
id选择器》class》标签
*/
#han{
color: #6660ff;
}
.ming{
color: #000;
}
h1{
color: red;
}
</style>
</head>
<body>
<h1 id="han" class="ming">标题1</h1>
<h1 class="ming">标题2</h1>
<h1 class="ming">标题3</h1>
<h1>标题4</h1>
<h1>标题5</h1>
</body>
优先级 id>class>标签
层次选择器
- 后代选择器:在某个元素后面所有元素
/*后代选择器*/
body p{
background: aquamarine;
}
- 子选择器 元素后的第一代
/*子选择器*/
body>p{
background: #6660ff;
}
- 相邻兄弟选择器 同辈的下一个
/*相邻兄弟选择器*/
.active+p{
background: aquamarine;
}
<p>p1</p>
<p class="active">p2</p>
<p>p3</p>
.active+p{}
选择的是class为active的标签 的下一个p标签
- 通用选择器 同辈的下所有
.active ~ p{
background: aquamarine;
}
选中的是cative类 下面的所有p标签
结构伪类选择器
/*选中ul的第一个子元素*/
ul li:first-child{
background: red;
}
/*ul的最后一个子元素*/
ul li:last-child{
background:#6660ff ;
}
/*选中p1:定位到p标签的父元素,选择当前的第二个元素(选中的元素需要是p标签,其他标签也同理)*/
p:nth-child(2){
background: blueviolet;
}
/*选中父元素下,p元素的第二个*/
p:nth-of-type(2){
background: yellow;
}
/*鼠标移到a标签上背景就会变*/
a:hover{
background:blueviolet ;
}
属性选择器
元素【】{}
= 绝对等于
*= 包含这个元素
^= 以这个开头
$= 以这个结尾
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.demo a{
float: left