我想要一些简单的例子来展示<div>和<span>的使用。我曾看到它们都被用来用id或类标记页面的一部分,但我感兴趣的是,是否有时会优先使用其中一种而不是另一种。
当前回答
在HTML中,有一些标记为内容添加结构或语义。例如,<p>标记用于标识一个段落。另一个例子是有序列表的<ol>标记。
如上面所示,当HTML中没有合适的标记时,通常会使用<div>和<span>标记。
<div>标记用于标识文档的块级节/除法,该节/除法前后都有换行符。
可以使用div标签的例子有页眉、页脚、导航等。然而在HTML 5中,这些标记已经提供了。
<span>标记用于标识文档的内联节/分。
例如,span标记可用于向元素添加内联象形文字。
其他回答
正如在其他回答中提到的,默认情况下div将被呈现为块元素,而span将在其上下文中内联呈现。但两者都没有任何语义价值;它们的存在允许您对任何给定的内容应用样式和标识。使用样式,可以使div像span一样,反之亦然。
div的一个有用的样式是内联块
例子:
http://dustwell.com/div-span-inline-block.html CSS显示:内联vs内联块
我曾在游戏网页项目中使用内联块取得了巨大的成功。
“块元素”的意义是隐含的,但从未明确说明。如果我们忽略所有的理论(理论是好的),那么下面是一个语用比较。以下几点:
<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不仅不应该内联使用,而且它根本不会产生想要的效果。
真正重要的区别已经在克里斯的回答中提到了。然而,这并不是对每个人都有明显的影响。
作为一个内联元素,<span>只能包含其他内联元素。因此下面的代码是错误的:
<span><p>This is a paragraph</p></span>
上面的代码无效。要包装块级元素,必须使用另一个块级元素(例如<div>)。另一方面,<div>只能在块级元素合法的地方使用。
此外,这些规则在(X)HTML中是固定的,它们不会因CSS规则的存在而改变!所以下面的代码也是错的!
<span style="display: block"><p>Still wrong</p></span>
<span><p style="display: inline">Just as wrong</p></span>
这很简单。
span的使用不会影响布局,因为它是内联的(在行中(不应该混淆,因为东西可以被换行)) 使用div会影响布局,里面的内容会出现在新行(block element)中,当你想添加的元素没有特殊的语义,而你想让它出现在新行中时,使用<div>。
为了完整起见,我建议你这样思考:
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.