8月4日零基础自学CSS笔记第1篇。
1. css概述
css 全称:层叠样式表
网页的内容,由 HTML 控制
网页的样式,由 CSS 控制
2. css语法
2.1 元素选择器:
选择器{
属性名1:属性值1;
属性名2:属性值2;
}
h1{
color:red;
font-size:12px;
}
2.2 类选择器:
常常制定一个类划分的多个元素
.className{
属性名1:属性值1;
属性名2:属性值2;
}
.text{
color:red;
}
<h1 class="text">hello world</h1>
2.3 id选择器:
常常只制定一个元素
#id{
属性名1:属性值1;
属性名2:属性值2;
}
#text{
color:red;
}
<h1 id="text">hello world</h1>
2.4 通配符选择器:
制定整个页面的所有标签
*{
属性名1:属性值1;
属性名2:属性值2;
}
3. 常用css属性
字体大小:font-size
(chrome浏览器:font-size最小值是12px)
字体颜色:color
宽度:width
(可以使用auto代替px与另一个值成比例匹配,防止图片形变)
高度:height
(可以使用auto代替px与另一个值成比例匹配,防止图片形变)
背景色:background-color
文本水平居中:text-align
文本行高(垂直居中):line-height
3. 更多选择器
层级选择器:selector1 selector2
组合选择器:selector1
,selector2
伪类选择器(增加行为):selector:hover
(hover是移动鼠标)
伪元素选择器(增加元素):selector::before
,selector::after
-除此之外还有很多选择器
4.1 层级选择器:selector1 selector2
用来指定某一个类下的选择器
<head>
<style>
/* 层级选择器 */
.box h1{
color:red;
}
</style>
</head>
<body>
<div class="box">
<h1>hello world</h1>
</div>
<div class="box2">
<h1>hello world</h1>
</div>
</body>
4.2 组合选择器:selector1
,selector2
同时选择selector1
和selector2
的样式
<head>
<style>
/* 层级选择器 */
/* .box h1{
color:red;
} */
/* 层级选择器+组合选择器 */
.box1 h1,.box1 h2{
color:red;
}
</style>
</head>
<body>
<div class="box1">
<h1>hello h1</h1>
<h2>hello h2</h2>
</div>
<div class="box2">
<h1>hello world</h1>
<h2>hello world</h2>
</div>
</body>
4.3 伪类选择器(增加行为):selector:hover
实现鼠标移动到某一个元素之上,让他的颜色改变
<head>
<style>
.btn:hover{
background-color: green;
}
</style>
</head>
<body>
<input class="btn" type="button" value="按钮">
</body>
光标移动上去呈现蓝色
4.4 伪元素选择器(增加元素):selector::before
,selector::after
在一个元素前后
<head>
<style>
h1::before{
content:"-----"
}
h1:after{
content:"-----"
}
</style>
</head>
<body>
<h1>
hello world
</h1>
<h1>
hello world
</h1>
</body>
将伪元素选择器
结合层级选择器
,组合选择器
后:
<head>
<style>
.box::before,.box::after{
content:"-----"
}
</style>
</head>
<body>
<h1 class="box">
hello world
</h1>
<h2 class="box">
hello world
</h2>
</body>
注意,css2版本:伪类选择器和伪元素选择器,都是一个冒号,css3版本:为了区分这两个选择,因此将伪元素选择器更改为2个冒号,但是浏览器兼容css2版本和css3版本,但是我们写的时候应该尽量遵守css3的代码规范。
5. 选择器权重
5.1 权重情况分析
相同选择器:后面的会覆盖前面的
不同选择器:ID(100)> CLASS(10)> element(1)
层级选择器:按多个选择器的权重累加计算
<head>
<style>
/* 10 + 100 = 110 */
.box #txt{
color:red;
}
/* 100 + 1 = 101 */
#box2 h1{
color:blue
}
</style>
</head>
<body>
<div class="box" id="box2">
<h1 class="title title2" id="txt">
hello world
</h1>
</div>
</body>
最后 hello world
会显示红色
5.2 设置最高权重
!important
在 css
属性后分号前加上该语句即可。
6. 引入 css 样式的方法
6.1 嵌入样式
即上述代码的书写格式,将 css 样式写成 style 标签放置在 head 标签内
6.2 内联样式/行内样式
不易维护,基本不使用,了解即可
<h1 style="color: red">
hello world
</h1>
6.3 外部样式(实际开发中大部分都使用外部样式)
将 css
代码写在 .css
文件中
<link rel="stylesheet" href="p5-05.css">
然后将该行代码放置在 .html
文件 的 head
标签内