css基本知识

CSS 是指层叠样式表 (Cascading Style Sheets),基本语法规则如下

CSS 由两个主要的部分构成:选择器,以及一条或多条声明

声明以大括号{ }括起来,一个申明包括属性和值,属性与值通过冒号分隔;多个声明通过分号;分隔

 

CSS注释以 "/*" 开始, 以 "*/" 结束,即/*注释内容*/

 

在html中插入CSS样式表的方法有三种:

1.外部样式表(External style sheet):即所有的样式单独写在一个.css文件中,在html文件的head部分通过link进行链接

<head>  <link rel="stylesheet" type="text/css" href="mystyle.css"></head>

其中href表示的是外部css文件的路径和名称

2.内部样式表(Internal style sheet):即写在html文件内,同样在head部分,但是是通过<style>······</style>进行引入的

<head> <style> body {background-image:url("images/back40.gif");} hr {color:red;} p {margin-left:20px;} </style> </head> 

3.内联样式(Inline style):即将css表现内容与html内容糅合在一起,需要在html标签内通过style=‘ ‘来引用

<p style="color:sienna;margin-left:20px">这是一个段落。</p>

对于一个html文件,可以同时使用多种css样式,此时显示优先级为内联样式 > 内部样式 > 外部样式 > 浏览器默认样式

 

id选择器和class选择器,属性都不要以数字开头

id 选择器为标有特定 id 的HTML元素指定特定的样式,以id属性来设置id选择器,以 "#" 来定义id选择器样式

<style> #para1 { text-align:center; color:red; } </style>······<p id="para1">Hello World!</p><p>这个段落不受该样式的影响。</p> 

class选择器可以在多个元素中使用,以class属性来设置class选择器,以 "." 来定义class选择器样式

<style> .center { text-align:center; }</style>······<h1 class="center">标题居中</h1><p class="center">段落居中。</p> 

也可以指定特定的html元素使用id和class

<style> p#para1 { text-align:left; color:red; } p.center { text-align:center; color:green; }</style>······<p id="para1">使用id选择器</p><p class="center">使用class选择器</p>

 

相关文章