当前位置: 移动技术网 > IT编程>网页制作>CSS > html和css入门 (二)

html和css入门 (二)

2018年10月19日  | 移动技术网IT编程  | 我要评论

css基础

什么是css

简单来说,层叠样式表(cascading style sheet)是一种专门用来控制界面外观风格的文档。

css发展历史

  1. 1996年 css 1.0 规范面世,其中加入了字体、样色等相关属性。
  2. 1998年 css 2.0 规范推出,这个版本的 css 也是最广为人知的一个版本。
  3. 2004年 css 2.1 规范推出,对 css 2.0 进行了一些小范围的修改,删除了一些浏览器支持不成熟的属性。
  4. 2010年 css 3.0 规范推出,将 css3 分成了不同的模块,例如盒子模型、背景和边框、文字特效等模块。

css使用方式

行内样式

<!doctype html>
<html lang="en">
    <head>
        <title>this is title</title>
    </head>
    <body>
        <p style="font-size: 16px; color: red;">my cat is very grumpy</p>
    </body>
</html>

行内样式需要写到标签的 style 属性值中。

内部样式表

<!doctype html>
<html lang="en">
    <head>
        <title>this is title</title>
        <style>
            p {
                font-size: 16px;
                color: red;
            }
        </style>
    </head>
    <body>
        <p>my cat is very grumpy</p>
    </body>
</html>

内部样式需要写到 <style> 标签中。

外部样式表

  • 链接式

将样式写到单独的文件中,文件的扩展名为 .css。例如,index.css 文件中有如下样式:

p {
    font-size: 16px;
    color: red;
}

然后通过 <link> 元素将 index.css 文件引入到页面中:

<!doctype html>
<html lang="en">
    <head>
        <title>this is title</title>
        <link rel="stylesheet" type="text/css" href="./index.css">
    </head>
    <body>
        <p>my cat is very grumpy</p>
    </body>
</html>
  • 导入式

创建 style1.css 文件,文件中有如下样式:

/* style1.css */
h1 {
    font-size: 32px;
    color: green;
}

创建 style2.css 文件,并使用 @import 指令将 style1.css 导入到 style1.css 文件中:

/* style2.css */
p {
    font-size: 16px;
    color: red;
}

最后,通过 <link> 元素将 style2.css 文件引入到页面中:

<!doctype html>
<html lang="en">
    <head>
        <title>this is title</title>
        <link rel="stylesheet" type="text/css" href="./style2.css">
    </head>
    <body>
        <h1>一级标题</h1>
        <p>my cat is very grumpy</p>
    </body>
</html>

定义在外部文件(外链样式):本教程中案例主要是通过这种形式定义样式。 在页面的头部定义(内联样式):通过这种形式定义的样式只在本页面内生效。 定义在特定的元素身上(行内样式):这种形式多用于测试,可维护性较差。

css基本语法

css 样式由一系列的规则集组成,规则集中有一条或多条样式声明,每条样式声明包含着一对属性名和属性值,属性名和属性值之间以冒号(:)隔开,样式规则之间以分号(;)隔开,最后一对样式声明后面可以省略分号。

基本选择器

标签选择器

p {
    font-size: 16px;
    color: red;
}

选择页面中所有的 <p> 元素,给它们设置字体大小和颜色。

class 选择器

.box {
    font-size: 20px;
    color: green;
}

选择页面中 class 属性值中包含 box 类名的所有元素,给它们设置字体大小和颜色。

id 选择器

#nav {
    font-size: 24px;
    color: blue;
}

选择页面中 id 属性值是 nav 的元素,给它设置字体大小和颜色。

通配符选择器

* {
    font-size: 24px;
    color: blue;
}

样式的优先级

  1. 行内样式的优先级最高

  2. 选择器的优先级根据权重计算

选择器id选择器class选择器标签选择器总权重
html body header h1 0 0 4 4
.page-header .title 0 2 0 20
#page-title 1 0 0 100

属性选择器权重与类相同,+ > ~ 权重为 0

  1. 在选择器权重相同的情况下,遵循就近原则,也就是说,谁距离目标元素近,应用哪个个样式。

  2. 使用 !important 声明调整样式的优先级

样式的来源

共有三种主要的样式来源:

  • 浏览器对html定义的默认样式。
  • 用户定义的样式。
  • 开发者定义的样式。

 

特别声明:本人也是小白,想让与我一样的初学者一起学习,写的不好的地方请见谅

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网