2015年1月26日 星期一

html 中div, span 的分別與用法

這是考古題:


 <div> <span> 的差別



div的定義:div, an abbreviation for ‘division’, is an HTML tag (otherwise known as an element). Used to create containers around groups of content on Web pages, it is usually given a unique id to distinguish it from other div elements on the same page.

SPAN
SPAN is an inline element and can be used within paragraphs, list items, etc



div 跟span都是在html中切割的區塊

一般使用上div會用在比較大的區塊內,而若是裡面要再切割,則使用span


也有看到有人的介紹是說:span一般的定義上只能放一些文字,而div因為是區塊,所以可以放圖片、段落等等,雖然實際上沒有人在鳥。


最主要的實用差別是在於css

div    display: block
span  display: inline

因此兩個<div>併排的時候會換行,但兩個<span>不會。



在HTML5之中,其實會更重視他們的原始意思,從語義的方法來理解。
但是最神奇的是似乎沒有人知道span從哪裡來的…大家只能使用考古學的方式來找出其意思。



一些相關的面試考題:

如果要用span來做div的功能:請問要怎麼辦?

(解答就是直接overwrite css即可)


如果div前面使用了float,要怎麼把它換回來?

 ans: 加上clear:both

或著是使用:after 來overwrite css也不錯。







P.S.:
div  是division 的縮寫,但我找不到span是什麼的縮寫

最接近的是這一段:  (from stackoverflow)

大致上是猜測他是從動詞"to span" 而來,但有人發現這其實是從其他的browser定義而來,最後才被加到html的定義中。

Pretty hard to find out what was going on in the minds of the creators of HTML4, where SPAN first appeared. I tracked down the original draft of the standard, but there is nothing said about the naming, only a definition:
SPAN is an inline element and can be used within paragraphs, list items, etc. when you want assign class or language information to a group of words. SPAN cannot be used to group block-level elements. SPAN has no inherent effect on rendering until you apply a style, e.g., via a style attribute, or a linked style sheet.
It's probably just derived from the verb 'to span'. But I would like to have found a reference:)
Update
Also from the HTML4 specification (the newest one this time):
Each version of HTML has attempted to reflect greater consensus among industry players so that the investment made by content providers will not be wasted and that their documents will not become unreadable in a short period of time.
Therefore, the SPAN element was probably first supported by a certain browser, after which it was taken over by other browsers and eventually adopted as a standard. So 10 points to the one who can name that browser and produce 199x IRC chat logs of that browser´s devs:)





沒有留言:

張貼留言