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


当前回答

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>只能包含其他内联元素。因此下面的代码是错误的:

<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>

Div是一个块元素,span是一个内联元素,它的宽度取决于它自己的内容,而Div不是

这很简单。

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.