The Difference Between Div and Span
居然 9 月了!!前陣子去面試前端實習生的時候,發現自己還有好多不熟悉的觀念,趁還沒開學趕快弄懂然後記錄下來~今天要介紹的是 div 跟 span 的差別,兩者都是 HTML 常見的 elements。
Type of Element
Div: block-level element
- always starts on a new line
- always takes full width available (stretches out to the left and right as far as it can)
- has a top and a bottom margin
Span: inline element
- does not start on a new line
- only takes as much width as necessary
- dose not have a top and a bottom margin
Example
<body>
<h1>This Is Div</h1>
<h2>Div starts on a new line, and takes full width available.</h2>
<a href="https://blog.joannefei.com/">Joanne's Blog!</a>
<div style="background-color: aliceblue;">Hello World</div>
<h1>This Is Span</h1>
<h2>Span dose not start on a new line, and only takes as much width as necessary.</h2>
<a href="https://blog.joannefei.com/">Joanne's Blog!</a>
<span style="background-color: antiquewhite;">Hello World</span>
</body>
Usage
Div
- often used as a container for other HTML elements
- can be used to style blocks of content when used together with CSS
Span
- used to mark up a part of a text, or a part of a document
- can be used to style parts of the text when used together with CSS
Example
<body>
<div style="background-color: rosybrown;">
<h1>This Is Div</h1>
<h2>Div is used as a container for other HTML elements, and can be used to style blocks of content.</h2>
</div>
<h1>This Is Span</h1>
<h2>Span is used to mark up <span style="color: red;">a part of a text, or a part of a document.</span></h2>
</body>