CSS 基础教程

1简介

1、CSS 概述
     1.1CSS 指层叠样式表
     1.2内容与表现分离

2、多重样式将层叠为一个
     2.1优先权
          2.1.1内联样式(在 HTML 元素内部)
          2.1.2内部样式表(位于 <head> 标签内部)
          2.1.3外部样式表
          2.1.4浏览器缺省设置

2基础语法

1、语法
     1.1由两个主要的部分构成:选择器,以及一条或多条声明。
selector {declaration1; declaration2; ... declarationN }
     选择器通常是您需要改变样式的 HTML 元素。
     每条声明由一个属性和一个值组成。
selector {property: value}



2、值的不同写法和单位
p { color: #ff0000; }

p { color: #f00; }

p { color: rgb(255,0,0); }
p { color: rgb(100%,0%,0%); }


3、记得写引号
     3.1如果值为若干单词,则要给值加引号:
p {font-family: "sans serif";}


4、多重声明
     4.1如果要定义不止一个声明,则需要用分号将每个声明分开。
p {
  text-align: center;
  color: black;
  font-family: arial;
}


3高级语法

1、选择器的分组
     1.1对选择器进行分组,这样,被分组的选择器就可以分享相同的声明。
h1,h2,h3,h4,h5,h6 {
  color: green;
  }


2、继承及其问题
     2.1根据 CSS,子元素从父元素继承属性。

4派生选择器

1、派生选择器
     1.1上下文选择器
     1.2派生选择器允许你根据文档的上下文关系来确定某个标签的样式。
li strong {
    font-style: italic;
    font-weight: normal;
  }

<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>

<ol>
<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>


5id 选择器

1、id 选择器
     1.1id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。
     1.2id 选择器以 "#" 来定义。
#red {color:red;}
#green {color:green;}

<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>


2、id 选择器和派生选择器
#sidebar p {
        font-style: italic;
        text-align: right;
        margin-top: 0.5em;
        }


6类选择器

1、在 CSS 中,类选择器以一个点号显示:
.center {text-align: center}

<h1 class="center">
This heading will be center-aligned
</h1>

<p class="center">
This paragraph will also be center-aligned.
</p>


2、和 id 一样,class 也可被用作派生选择器:
.fancy td {
        color: #f60;
        background: #666;
        }

td.fancy {
        color: #f60;
        background: #666;
        }

<td class="fancy">



7属性选择器

1、对带有指定属性的 HTML 元素设置样式。

2、属性选择器
[title]
{
color:red;
}


3、属性和值选择器
[title=W3School]
{
border:5px solid blue;
}


4、属性和值选择器 - 多个值
[title~=hello] { color:red; }


5、设置表单的样式
     5.1属性选择器在为不带有 class 或 id 的表单设置样式时特别有用
input[type="text"]
{
  150px;
  display:block;
  margin-bottom:10px;
  background-color:yellow;
  font-family: Verdana, Arial;
}

input[type="button"]
{
  120px;
  margin-left:35px;
  display:block;
  font-family: Verdana, Arial;
}


6、CSS 选择器参考手册
选择器描述[attribute]用于选取带有指定属性的元素。[attribute=value]用于选取带有指定属性和值的元素。[attribute~=value]用于选取属性值中包含指定词汇的元素。[attribute|=value]用于选取带有以指定值开头的属性值的元素,该值必须是整个单词。[attribute^=value]匹配属性值以指定值开头的每个元素。[attribute$=value]匹配属性值以指定值结尾的每个元素。[attribute*=value]匹配属性值中包含指定值的每个元素。

8创建

1、如何插入样式表
     1.1外部样式表
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>


     1.2内部样式表
<head>
<style type="text/css">
  hr {color: sienna;}
  p {margin-left: 20px;}
  body {background-image: url("images/back40.gif");}
</style>
</head>


     1.3内联样式
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>
原文地址:https://www.cnblogs.com/cnmotive/p/3139021.html