TOC

This article is currently in the process of being translated into Chinese (~7% done).

HTML Basics:

Block & Inline elements

我們已經看了一些構成網頁的HTML5元素,接下來是時候要介紹HTML5元素的另外一種性質。有兩種不同型態的元素,分別是行內元素和區塊元素。他們的差異在瀏覽器渲染元素的方式。

區塊元素

區塊元素,顧名思義,會被渲染為一個長方形的區塊。區塊元素的寬度會盡可能的大,而不會跨行,其高度與寬度都可以被調整。區塊元素內可以包含行內元素和其他的區塊元素。

行內元素

行內元素作為文件中的一部分,通常其高度和寬度是不能改變的。而只有行內元素能放在行內元素之中。不過也有比較特殊的情況,雖然段落元素(<p> 元素)是區塊元素,但只有行內元素能放在 <p> 元素之中。

段落元素 <p></p> 是區塊元素,而粗體元素 <b>是行內元素。

範例

區塊元素當中最被廣泛使用的是 <div> ,其中 div 是 division 的縮寫,意為區域、隔間(中文譯註:div 的中譯並沒有被普遍使用,習慣上是以 div 稱呼)。<div> 元素是用來分隔網頁中不同內容的區塊元素。想像在你的網頁中有兩則更新,每則更新都包含了標題、你的名字,以及發布的日期。如下方的範例所示:

Just Another Day
Written by Christina
On January 11th

This is my second blog entry, and I just wanted to check in on you

My First Blog Entry
Written by Christina
On January 10th

I’m so happy to write my first blog entry – yay!

As you can see, there is two blog-entries and we divide them using a block element - in this case is chose a <div>. Inside the block element is another block element, the paragraph (<p>). Using just only the most necessary markup, the HTML for your webpage would look like this:

<!DOCTYPE html>
<html>
<head>
	<title>Your first HTML5 Document</title>
</head>
<body>
	<div>
		<p>Just Another Day<br />
		Written by Christina<br />
		On January 11th
		</p>
		<p>This is my second blog entry, and I just wanted to check in on you
		</p>
	</div>
	<div>
		<p>My First Blog Entry<br />
		Written by Christina<br />
		On January 10th
		</p>
		<p>
		I’m so happy to write my first blog entry – yay!
		</p>
	<div>
</body>
</html>

The <div>-elements are used to diversify the two blog entries. Inside each of the <div>-elements is two paragraphs consisting of title & author and the actual entry.

The <div> element is widely used as a container that can apply formatting anywhere you want on your webpage. The limitation is that the <div> elements do not tell you anything about the actual content. So the browser knows that it has found a separate section, but not what kind of section. In HTML5 a lot of new elements have been introduced and some of them are here to replace the use of the <div> - see the articles about the new semantic elements to dig in to semantic markup.

I have previously talked about nesting elements and the fact that the <p> elements is inside the <div> elements is an example of nested elements.

What you have learned

  • Block elements are like squares
  • Inline elements have no breaks associated with the element
  • You can nest block elements inside other block elements
  • But you cannot nest block elements inside inline elements
  • The paragraph is the only block element that must only contain inline elements
  • The <div> elements is currently used as a container, but new HTML5 elements is here to change that
This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!