菜单
首页/博客/CSS 入门

CSS 入门

CSS是什么

CSS 定义了如何显示 HTML 元素。

因为多个样式定义可层叠为一个,所以叫层叠样式表(Cascading Style Sheets)。

CSS在MDN上的定义:

层叠样式表(Cascading Style Sheets,缩写为 CSS)是一种样式表语言,用来描述 HTML 或 XML(包括如 SVG、MathML 或 XHTML 之类的 XML 分支语言)文档的呈现方式。CSS 描述了在屏幕、纸质、音频等其他媒体上的元素应该如何被渲染的问题。

为什么用CSS

CSS可以从HTML中分离出样式的定义。

基本语法

规则集

css的基本元素是规则集(ruleset,简称为规则)。一段css代码可以有多个规则。

rule
rule

一条规则包括选择器(selector)和声明(declaration)。声明可以有多个。

selector {
    declaration;
    declaration;
}
selector {
    declaration;
    declaration;
}

一个声明包括属性(properties)和属性值(property value)。

selector {
    properties: property_value;
    properties: property_value;
}
selector {
    properties: property_value;
    properties: property_value;
}

注释

CSS的注释标注在 /* 和 */ 之间,可以换行。

最后来看一段完整的css代码。

/*注释1*/
mytag {
    color: red;
    width: 256px;
}
.myClass {
    /*注释2*/
    color: blue;
    heigth: 64px;
}
#myID {
    color: yellow;
    heigth: 16px;
}