我想要一些简单的例子来展示<div>和<span>的使用。我曾看到它们都被用来用id或类标记页面的一部分,但我感兴趣的是,是否有时会优先使用其中一种而不是另一种。


当前回答

为了完整起见,我建议你这样思考:

There are lots of block elements (linebreaks before and after) defined in HTML, and lots of inline tags (no linebreaks). But in modern HTML all elements are supposed to have meanings: a <p> is a paragraph, an <li> is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote> whether the content was a quote or not. So, what do you do when there is no meaning to the thing you're trying to do? There's no meaning to a 400px-wide column, is there? You just want your column of text to be 400px wide because that suits your design. For this reason, they added two more elements to HTML: the generic, or meaningless elements <div> and <span>, because otherwise, people would go back to abusing the elements which do have meanings.

其他回答

我想说,如果你懂一点西班牙语,看看这一页,在那里有适当的解释。

然而,一个快速的定义是,div是用于划分部分,span是用于将某种样式应用到另一个块元素中的元素,如div。

<div>是块级元素,<span>是行内元素。

如果你想对一些内联文本做一些事情,<span>是正确的选择,因为它不会像<div>那样引入换行符。


正如其他人所注意到的,这些都隐含着一些语义,最重要的事实是,<div>暗示了文档中的逻辑划分,类似于文档的一个部分或其他内容,例如:

<div id="Chapter1">
   <p>Lorem ipsum dolor sit amet, <span id="SomeSpecialText1">consectetuer adipiscing</span> elit. Duis congue vehicula purus.</p>
   <p>Nam <span id="SomeSpecialText2">eget magna nec</span> sapien fringilla euismod. Donec hendrerit.</p> 
</div>

这很简单。

span的使用不会影响布局,因为它是内联的(在行中(不应该混淆,因为东西可以被换行)) 使用div会影响布局,里面的内容会出现在新行(block element)中,当你想添加的元素没有特殊的语义,而你想让它出现在新行中时,使用<div>。

“块元素”的意义是隐含的,但从未明确说明。如果我们忽略所有的理论(理论是好的),那么下面是一个语用比较。以下几点:

<p>This paragraph <span>has</span> a span.</p>
<p>This paragraph <div>has</div> a div.</p>

生产:

This paragraph has a span.

This paragraph

has
a div.

这表明div不仅不应该内联使用,而且它根本不会产生想要的效果。

在HTML中,有一些标记为内容添加结构或语义。例如,<p>标记用于标识一个段落。另一个例子是有序列表的<ol>标记。

如上面所示,当HTML中没有合适的标记时,通常会使用<div>和<span>标记。

<div>标记用于标识文档的块级节/除法,该节/除法前后都有换行符。

可以使用div标签的例子有页眉、页脚、导航等。然而在HTML 5中,这些标记已经提供了。

<span>标记用于标识文档的内联节/分。

例如,span标记可用于向元素添加内联象形文字。