对CSS学习的总结
我的开发工具与所用浏览器
开发工具选用vs code,浏览器选择Firefox。
CSS的内容
1.CSS是级联样式表(Cascading Style Sheets)的缩写。
2.CSS的语法与使用
(1)一条CSS样式规则由两个主要的部分构成:选择器,以{}包裹的一条或多条声明:
p{//选择器
color:red;//声明,由属性和值组成
text-align:center;
}
选择器有元素选择器、id选择器和class选择器。
(2)CSS的使用有三种方法,外部样式表,内部样式表和内联样式,外部样式表要在同一目录下新建一个样式表文件mycss.css,而内部样式表则是将样式放在html文件中,例如:
<style>
body {
background-color: linen;
text-align: center;
}
h1 {
color: red;
}
.haha {
margin-top: 100px;
color: chocolate;
font-size: 50px;
}
</style>
其中,内联样式表最不灵活所以不推荐使用。
3.颜色、尺寸与对齐
(1)颜色
我们可以采用颜色名称也可以使用颜色RGB16进制值,来设定前景或背景的颜色。
<h3 style="background-color:Tomato;">Tomato</h3>
<h3 style="background-color:#ff0000;">#ff0000</h3>
(2)尺寸
我们可以用 height 和 width 设定元素内容占据的尺寸。常见的尺寸单位有:像数 px,百分比 %等。
先新建样式表文件
.example-1 {
width: 100%;//占据全部宽度
height: 200px;//高两百像素
background-color: powderblue;
text-align: center;
}
再新建HTML文件
<html>
<head>
<link rel="stylesheet" href="./mycss.css">//样式表地址
</head>
<body>
<div class="example-1">//引用样式表
任意文字
</div>
</body>
</html>
(3)对齐
对于元素中的文本,我们可以简单的设置text-align属性为left, center, right即可。
p{color:red;text-align:left;//左对齐}
4.盒子模型
盒子模型指的是一个 HTML 元素可以看作一个盒子。从内到外,这个盒子是由内容 content, 内边距 padding, 边框 border, 外边距 margin构成的。
新建CSS文件
.box1 {
height: 200px;//内容高度200像素
width: 200px;//内容宽度200像素
background-color:#615200;//背景颜色
color: aliceblue;//颜色
border: 10px solid red;//边框宽10像素,红色实线
padding: 25px;//内边距25像素
margin: 25px;//外边距25像素
}
再新建HTML文件
<html>
<head>
<link rel="stylesheet" href="./mycss.css">
</head>
<body>
<div class="box1">内容</div>
</body>
</html>
5.定位
用position属性对元素进行定位,具有以下值:
static//静态
relative//相对
fixed//固定
absolute//绝对
6.浮动
在一个区域或容器内,我们可以设置float属性让某元素水平方向上向左或右进行移动,其周围的元素也会重新排列。
<html>
<head>
<style>
.example-float-right {
float: right;//浮动
}
</style>
</head>
<body>
<img src="图片" class="example-float-right" alt="">
<p>内容</p>
</body>
</html>
7.不透明度
通过opacity对元素设置不透明度,取值在0.0~1.0之间,值越小越透明。
8.组合选择器
(1)后代选择器
以空格作为分隔,如:.haha p 代表在div元素内有.haha这种类的所有元素。
<html>
<head>
<style>
.haha p {
background-color: yellow;//背景为黄色
}
</style>
</head>
<body>
<div class="haha">
<p>1 in the div .haha.</p>
<p>2 in the div .haha>.</p>
<span>
<p>3 in the div .haha.</p>
</span>
</div>
<p>4. Not in a div .haha.</p>
<p>5. Not in a div .haha.</p>
</body>
</html>
(2)子选择器
也称为直接后代选择器,以>
作为分隔,如:.haha > p
代表在有.haha类的元素内的直接<p>
元素。
<html>
<head>
<style>
.haha > p {
background-color: yellow;
}
</style>
</head>
<body>
<div class="haha">
<p>1 in the div .haha.</p>
<p>2 in the div .haha.</p>
<span>
<p>3 in the div .haha - it is descendant but not immediate child.</p>
</span> <!-- not Child but Descendant -->
</div>
<p> 4. Not in a div .haha.</p>
<p>5. Not in a div .haha.</p>
</body>
</html>
9.伪类和伪元素
伪类(pseudo-class)或伪元素(pseudo-element)用于定义元素的某种特定的状态或位置等。
使用伪类/伪元素的语法如下:
// 选择器后使用 : 号,再跟上某个伪类/伪元素
selector:pseudo-class/pseudo-element {
property:value;
}