HTML Div and Span

The HTML div and span elements are generic containers. They carry no meaning of their own; they exist so you can group content and target it with CSS or JavaScript.

Using div to Group Blocks

<div> is a block container. Wrap related elements in it to style or position them together.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>div</title>
<style>.card { border: 1px solid #ddd; border-radius: 8px; padding: 12px; width: 220px; }</style></head>
<body>
  <div class="card">
    <h3>Coffee Beans</h3>
    <p>Medium roast, 1 kg.</p>
    <p><strong>$22.00</strong></p>
  </div>
</body>
</html>

Using span for Inline Text

<span> is an inline container used to style part of a sentence.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>span</title>
<style>.price { color: #16a34a; font-weight: bold; }</style></head>
<body>
  <p>Today only: almonds for <span class="price">$12</span> per bag.</p>
</body>
</html>

Div vs Span

  • div is block level: starts on a new line, full width
  • span is inline: flows within text
  • Both have no semantic meaning
  • A div may contain spans, but a span should not contain a div

Prefer Semantic Elements When Possible

Before reaching for a <div>, ask whether a meaningful element fits: <header>, <nav>, <main>, <article>, <section>, <aside> or <footer>. Use div only when no semantic element describes the content. The next lessons cover these elements.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Semantic vs div</title></head>
<body>
  <!-- Less clear -->
  <div class="nav"><a href="#">Home</a></div>
  <!-- Better -->
  <nav><a href="#">Home</a></nav>
</body>
</html>

Frequently asked questions

What is the difference between div and span?

A div is a block-level container for sections of content; a span is an inline container for parts of text. Neither adds meaning.

Is using too many divs bad?

Excessive divs ("div soup") make code harder to read and less accessible. Use semantic elements where they fit and divs only for styling hooks.

Can I make a span behave like a block?

Yes, with CSS display: block or display: inline-block, though it is often clearer to use a div.