一.插入样式表
有3种方法:外部样式表,内部样式表,内联样式。
1.外部样式表:需要一个单独的.css文件
样式需要应用于很多页面时,外部样式表将是理想的选择。在使用外部样式表的情况下,你可以通过改变一个文件来改变整个站点的外观。每个页面使用 <link>
标签链接到样式表。 <link>
标签在(文档的)头部:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
浏览器会从文件 mystyle.css 中读到样式声明,并根据它来格式文档。
创建一个.css文件,文件不能包含任何HTML标签
hr{color:red}
p{text-align: center;}
body{background-color: white;}
这个文件保存为mystyle.css就能在上面的html文件中调用了
2.内部样式表:head标签中使用style标签
单个文档需要特定样式,使用style标签在头部定义
<head>
<style>
hr{color: sienna;}
p{margin-left: 20px;}
body
{
background: url("1.jpg") no-repeat;
background-size: 50%;
background-color: sienna;
}
</style>
</head>
一个属性算一个声明,用分号隔开
这里url()里的链接的图片:和这个html文档在同一个文件夹内;或者有一个准确的URL地址
背景色background-color在最后一层,不然背景色有可能看不见
3.内联样式:直接在相关标签使用style
当样式仅需要在一个元素上应用一次时,要使用内联样式
<p style="color: sienna;margin-left: 20px;">这是一个段落。</p>
4.多重样式
比如外部和内部都有针对同一个元素的样式表
外部:
h3
{
color:red;
text-align:left;
font-size:8pt;
}
内部:
h3
{
text-align:right;
font-size:20pt;
}
最后结果:
color:red;
text-align:right;
font-size:20pt;
即颜色属性将被继承于外部样式表,而文字排列(text-alignment)和字体尺寸(font-size)会被内部样式表中的规则取代。
!!!多重样式优先级:
(内联样式)Inline style > (内部样式)Internal style sheet >(外部样式)External style sheet > 浏览器默认样式
!!!如果外部样式放在内部样式的后面,则外部样式将覆盖内部样式。
二.背景
CSS属性定义背景效果:
background-color/image/repeat/attachment/position
①背景颜色:background-color 属性定义了元素的背景颜色。页面的背景颜色使用在body的选择器中:
body {background-color:#b0c4de;}
②背景图:
background-image 属性描述了元素的背景图像.
默认情况下,背景图像进行平铺重复显示,以覆盖整个元素实体.
body{
background-image: url("https://static.runoob.com/images/mix/paper.gif");
background-color: #cccccc;
}
③水平或垂直平铺:默认情况下 background-image 属性会在页面的水平或者垂直方向平铺。
水平平铺:background-repeat:repeat-x;
垂直平铺:background-repeat:repeat-y;
不平铺:background-repeat:no-repeat;
④图像在背景中的位置background-postion
⑤简写以上:
可以将这些属性合并在同一个属性中。背景颜色的简写属性为 “background”:
body {background:#ffffff url('img_tree.png') no-repeat right top;}
以上属性无需全部使用,你可以按照页面的实际需要使用.
⑥背景图片固定,不随鼠标滚动
background-attachment:fixed
{background:
url("https://static.runoob.com/images/mix/smiley.gif")
no-repeat
fixed;
}
补充知识
①<hr>
画一条水平线,默认情况下长度=浏览器宽度,也可以用width设置
②属性值和单位之间没有空格:20px(对) 20 px(错)