为了让网页元素的样式更加丰富,也为了让网页的内容和样式能拆分开,CSS由此思想而诞生,CSS是 Cascading Style Sheets 的首字母缩写,意思是层叠样式表。有了CSS,html中大部分表现样式的标签就废弃不用了,html只负责文档的结构和内容,表现形式完全交给CSS,html文档变得更加简洁。
css基本语法
css的定义方法是:
选择器 { 属性:值; 属性:值; 属性:值;}
例:
div{
width:100px;
height:100px;
background:gold;
}
一、css引入页面的三种方式:
1、内联式:通过标签的style属性,把样式写在标签中
例:
<h1 style="width:200px;height:200px;background:red">这是一个h1标题</h1>
2、内嵌式:通过style标签,把样式写在head标签中
例:
<head>
<style>
p{width:200px;height:200px;background:gold;}
</style>
</head>
3、外链式:外部创建一个css文件,页面通过link标签引入
例:
<link rel="stylesheet" href="css/main.css" target="_blank" rel="external nofollow" >
二、css六种选择器:
1、标签选择器:写法和标签名相同,会选择所有的标签
例:
div{color:red}
2、类选择器:名称任意,名称前需要加“.”,标签通过class属性引用
例:
.blue{color:blue}
3、层级选择器:通过层级关系匹配标签
例:
.con span{color:red}
4、Id选择器: 通过id名称来选择标签(一般不用)
例:
#div01{
width:200px;
height:200px;
background:gold;
}
5、组选择器: 将通过的样式抽取出来写在一起,选择器之间用“,”隔开
例:
.box01,.box02,.box03{
width: 200px;
height: 200px;
}
.box01{
background:gold;
}
.box02{
background:red;
}
.box03{
background:orange;
}
6、伪类选择器: 定义鼠标悬停时标签的样式
例:
.link01:hover{
color:red;
}
三、css常用样式:属性样式列表
css属性
布局常用样式属性:
width 设置元素(标签)的宽度,如:width:100px;
height 设置元素(标签)的高度,如:height:200px;
background 设置元素背景色或者背景图片,如:background:gold; 设置元素背景色为金色
border 设置元素四周的边框,如:border:1px solid black; 设置元素四周边框是1像素宽的黑色实线
以上也可以拆分成四个边的写法,分别设置四个边的:
border-top 设置顶边边框,如:border-top:10px solid red;
border-left 设置左边边框,如:border-left:10px solid blue;
border-right 设置右边边框,如:border-right:10px solid green;
border-bottom 设置底边边框,如:border-bottom:10px solid pink;
padding 设置元素包含的内容和元素边框的距离,也叫内边距,如padding:20px;padding是同时设置4个边的,也可以像border一样拆分成分别设置四个边:padding-top、padding-left、padding-right、padding-bottom。
margin 设置元素和外界的距离,也叫外边距,如margin:20px;margin是同时设置4个边的,也可以像border一样拆分成分别设置四个边:margin-top、margin-left、margin-right、margin-bottom。
float 设置元素浮动,浮动可以让块元素排列在一行,浮动分为左浮动:float:left; 右浮动:float:right;
文本常用样式属性一:
color 设置文字的颜色,如: color:red;
font-size 设置文字的大小,如:font-size:12px;
font-family 设置文字的字体,如:font-family:'微软雅黑';为了避免中文字不兼容,一般写成:font-family:'Microsoft Yahei';
font-weight 设置文字是否加粗,如:font-weight:bold; 设置加粗 font-weight:normal 设置不加粗
line-height 设置文字的行高,如:line-height:24px; 表示文字高度加上文字上下的间距是24px,也就是每一行占有的高度是24px
text-decoration 设置文字的下划线,如:text-decoration:none; 将文字下划线去掉
text-align 设置文字水平对齐方式,如text-align:center 设置文字水平居中
text-indent 设置文字首行缩进,如:text-indent:24px; 设置文字首行缩进24px