css基本语法
css的定义方法是:选择器 { 属性:值; 属性:值; 属性:值;}
选择器是将样式和页面元素关联起来的名称,属性是设置的样式名称,每个属性有一个或多个值,例如 div标签:
div{width:100px; height:100px; color:red;}
css页面引入方法
1、外联式:通过link标签,链接到外部样式表到页面中。
<link rel="stylesheet" type="text/css" href="css/main.css">
2、嵌入式:通过style标签,在网页上创建嵌入的样式表。
<style type="text/css">
div{ width:100px; height:100px; color:red }
......
</style>
3、内联式:通过标签的style属性,在标签上直接写样式。
<div style="width:100px; height:100px; color:red ">......</div>
css选择器
常用的选择器有如下几种:
1、标签选择器
标签选择器,此种选择器影响范围大,建议尽量应用在层级选择器中。如下页面中所有div标签都会受到影响
div{width:100px; height:100px; color:red;}
2、id选择器
通过id名来选择元素且id名称不能重复,以# 打头定义。id选择器一般是程序和页面交互时使用
#box{color:red}
...
<div id="box">....</div> <!-- 对应以上一条样式,其它元素不允许应用此样式 -->
3、类选择器
通过类名来选择元素,一个类可应用于多个元素,一个元素上也可以使用多个类,应用灵活,可复用,是css中应用最多的一种选择器。
以 . 打头定义
.red{color:red}
.big{font-size:20px}
.mt{margin-top:10px}
<div class="red">....</div>
<h1 class="red big mt">....</h1>
<p class="red mt">....</p>
4、层级选择器
主要应用在选择父元素下的子元素,或者子元素下面的子元素,可与标签元素结合使用,减少命名,同时也可以通过层级,防止命名冲突。
层级选择器一般最高到四层
.box span{color:red}
.box .red{color:pink}
.red{color:red}
<div class="box">
<span>....</span>
<a href="#" class="red">....</a>
</div>
<h3 class="red">....</h3>
5、组选择器
多个选择器,如果有同样的样式设置,可以使用组选择器,各选择器之间用逗号隔开。各选择器自己有特殊属性可以单独再设置
.box1,.box2,.box3{width:100px;height:100px}
.box1{background:red}
.box2{background:pink}
.box2{background:gold}
<div class="box1">....</div>
<div class="box2">....</div>
<div class="box3">....</div>
6、伪类及伪元素选择器
常用的伪类选择器有hover,表示鼠标悬浮在元素上时的状态,
伪元素选择器有before和after,它们可以通过样式在元素中插入内容。
.box1:hover{color:red} .box2:before{content:'行首文字';} .box3:after{content:'行尾文字';} <div class="box1">....</div> <div class="box2">....</div> <div class="box3">....</div>
2018年8月7日