CSS 语法

2021-04-20 13:47:14 更新

目录:

CSS 语法规则

CSS 语法规则由两个主要的部分构成:选择器,以及一条或多条CSS声明(声明组)。每条声明由一个属性和一个值组成。

p {
  color: red;
  text-align: center;
}



内容:

CSS 语法规则由两个主要的部分构成:选择器,以及一条或多条CSS声明(声明组)。 选择器通常是您需要改变样式的 HTML 元素。每条声明由一个属性和一个值组成,属性(property)是您希望设置的样式属性(style attribute);每个属性有一个,属性和值被冒号分开。CSS声明总是以分号(;)结束,声明组以大括号({})括起来。

<html>
    <head>
        <style>
            body{background-color:yellow;}
            h1{font-size:36pt;}
            h2{color:blue;}
            p{margin-left:50px;}
        </style>
    </head>
    
    <body>    
        <h1>This header is 36 pt</h1>
        <h2>This header is blue</h2>
        
        <p>This paragraph has a left margin of 50 pixels</p> 
    </body>
</html>
<html>
    <head>
        <style>
            body {background-color:tan;}
            h1   {color:maroon;font-size:20pt;}
            hr   {color:navy;}
            p    {font-size:11pt;margin-left:15px;}
            a:link    {color:green;}
            a:visited {color:yellow;}
            a:hover   {color:black;}
            a:active  {color:blue;}
        </style>
    </head>
    
    <body>
        
        <h1>This is a header 1</h1>
        <hr>
        
        <p>You can see that the style 
        sheet formats the text</p>
        
        <p><a href="https://www.itwenda.com"  target="_blank">This is a link</a></p>
        
    </body>
</html>

CSS 语法


CSS 规则集(rule-set)由选择器和声明块组成:


CSS 选择器

选择器指向您需要设置样式的 HTML 元素。

声明块包含一条或多条用分号分隔的声明。

每条声明都包含一个 CSS 属性名称和一个值,以冒号分隔。

多条 CSS 声明用分号分隔,声明块用花括号括起来。


实例

在此例中,所有 <p> 元素都将居中对齐,并带有红色文本颜色:

p {
  color: red;
  text-align: center;
}

例子解释


    p 是 CSS 中的选择器(它指向要设置样式的 HTML 元素:<p>)。

    color 是属性,red 是属性值

    text-align 是属性,center 是属性值



关注公众号,了解更多it技术(it问答网