目录
一、语法
CSS声明总是以分号 ; 结束,声明总以大括号 {} 括起来
p
{
color:red;
text-align:center;
}
CSS注释以 /* 开始, 以 */ 结束
二、id 选择器
id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。
HTML元素以id属性来设置id选择器,CSS 中 id 选择器以 "#" 来定义。
ID属性不要以数字开头,数字开头的ID在 Mozilla/Firefox 浏览器中不起作用。
<style>
#para1
{
text-align:center;
color:red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
</body>
三、class 选择器
class 选择器用于描述一组元素的样式,class 选择器有别于id选择器,class可以在多个元素中使用。
class 选择器在 HTML 中以 class 属性表示, 在 CSS 中,类选择器以一个点 . 号显示。
<style>
.center
{
text-align:center;
}
</style>
</head>
<body>
<h1 class="center">标题居中</h1>
<p class="center">段落居中。</p>
</body>
指定特定的 HTML 元素使用 class。
<style>
p.center
{
text-align:center;
}
</style>
</head>
<body>
<h1 class="center">这个标题不受影响</h1>
<p class="center">这个段落居中对齐。</p>
</body>
多个 class 选择器可以使用空格分开:
<style>
.center {
text-align:center;
}
.color {
color:#ff0000;
}
</style>
</head>
<body>
<h1 class="center">标题居中</h1>
<p class="center color">段落居中,颜色为红色。</p>
</body>
四、背景
1.背景颜色
background-color 属性定义了元素的背景颜色.
页面的背景颜色使用在body的选择器中:
<style>
body
{
background-color:#b0c4de;
}
</style>
CSS中,颜色值通常以以下方式定义:
十六进制 - 如:"#ff0000"
RGB - 如:"rgb(255,0,0)"
颜色名称 - 如:"red"
2.背景图像
background-image 属性描述了元素的背景图像.
默认情况下,背景图像进行平铺重复显示,以覆盖整个元素实体.
<style>
body
{
background-image:url('paper.gif');
background-color:#cccccc;
}
</style>
1.背景图像 - 水平或垂直平铺
默认情况下 background-image 属性会在页面的水平或者垂直方向平铺。
如果图像只在水平方向平铺 (repeat-x), 页面背景会更好些
<style>
body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}
</style>
2.背景图像- 设置定位与不平铺
不想让图像平铺
<style>
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
}
</style>
可以利用 background-position 属性改变图像在背景中的位置
<style>
body
{
background-image:url('https://static.jyshare.com/images/mix/img_tree.png');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
}
</style>
3.背景- 简写属性
<style>
body
{
background:#ffffff url('img_tree.png') no-repeat right top;
margin-right:200px;
}
</style>
当使用简写属性时,属性值的顺序为::
background-color
background-image
background-repeat
background-attachment
background-position
4.背景属性
属性 | 描述 | 值 |
background | 简写属性,作用是将背景属性设置在一个声明中。 | |
background-attachment | 背景图像是否固定或者随着页面的其余部分滚动。 | scroll 背景图片随着页面的滚动而滚动,这是默认的。 fixed 背景图片不会随着页面的滚动而滚动。 local 背景图片会随着元素内容的滚动而滚动。 initial 设置该属性的默认值。 Inherit 指定 background-attachment 的设置应该从父元素继承。 |
background-color | 设置元素的背景颜色。 | |
background-image | 把图像设置为背景。 | |
background-position | 设置背景图像的起始位置。 | |
background-repeat | 设置背景图像是否及如何重复。 |