HTML超文本标记语言(五)——块元素和类

一、块元素及其作用

     HTML元素可分为块元素(block level element)和内联元素(inline element)。

     块元素:块元素在浏览器显示时,通常以新行开始和结束。如<h1>、<p>、<ul>、<table>等;

     内联元素:通常在显示时,不会以新行开始。如<b>、<td>、<img>、<a>等。

二、<div>元素

     <div>是块级元素,没有特定含义,可用于组合其他HTML元素的容器。

    1、定义:<div>标签可以把文档分割为独立的、不同的部分。使用<div>来组合块级元素,这样就可以使用样式(CSS)对它们进行格式化。

    2、用法:可以对<div>元素应用class或id属性,一般只用其中的一种。class用于元素组(某一类相似的元素),id用于标识单独的唯一的元素。

 1 <html>
 2 <body>
 3 <h3>This is a header!</h3>
 4 <p>This is a paragraph!!</p>
 5 <div style="color:#00FF00">
 6   <h3>This is a header!</h3>
 7   <p>This is a paragraph!</p>
 8 </div>
 9 </body>
10 </html>
div 块元素

 1 <html>
 2 <body>
 3   <h2>NEWS WEBSITE</h2>
 4   <p>some text. some text. some text...</p>
 5   ...
 6   <div class="news">
 7    <h3>News headline 1</h3>
 8    <p>some text. some text. some text...</p>
 9     ...
10   </div>
11   <div class="news">
12    <h3>News headline 2</h3>
13    <p>some text. some text. some text...</p>
14     ...
15   </div>
16    ...
17 </body>
18 </html>
div元素class属性

    上面这段 HTML 模拟了新闻网站的结构。其中的每个 div 把每条新闻的标题和摘要组合在一起,也就是说,div 为文档添加了额外的结构。同时,由于这些 div 属于同一类元素,所以可以使用 class="news" 对这些 div 进行标识,这么做不仅为 div 添加了合适的语义,而且便于进一步使用样式对 div 进行格式化,可谓一举两得。

三、<span>元素

    <span>是内联元素,也没有特定含义,可用作文本的容器。

    1、用法:

<p><span>some text.</span>some other text.</p>

    如果不对span应用样式,span元素中的文本与其他文本不会有任何视觉上的差异。

    可以为span应用id或class属性。

    2、应用样式举例

    如果文档中多次出现“提示”字样,可以搭配span和CSS为其指定特定样式。

    HTML:

<p class="tips"><span>提示:</span>其他文字……</p>

    CSS:

p.tips span{
               font-weight:bold;
               color:#ff9955;
}

意即:class名为tips的p元素里的span元素的样式。

 四、类

    对HTML进行分类(设置类),使我们能够为元素的类定义CSS样式。为相同的类设置相同的样式,或者为不同的类设置不同的类。

1、分类块级元素

    设置<div>元素的类,使我们能为相同的<div>元素设置相同的类。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <style>
 5 .cities {
 6           background-color:black;
 7           color:white;
 8           margin:10px;
 9           padding:10px;
10 }
11 </style>
12 </head>
13 <body>
14 <div class="cities">
15   <h2>London</h2>
16   <p>London is the capital city of England.</p>
17 </div>
18 <div class="cities">
19   <h2>Paris</h2>
20   <p>Paris is the capital and most populous city of France.</p>
21 </div>
22 <div class="cities">
23   <h2>Tokyo</h2>
24   <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area</p>
25 </div>
26 </body>
27 </html>
设置div元素的类

2、分类行类元素

    设置 <span> 元素的类,能够为相同的 <span> 元素设置相同的样式。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <style>
 5 span.red {
 6          color:red;           
 7 }
 8 </style>
 9 </head>
10 <body>
11   <h1>我的<span class="red">重要的</span>标题</h1>
12 </body>
13 </html>
设置span元素的类

原文地址:https://www.cnblogs.com/haidaojiege/p/6650906.html