Containers

HTML Containers: div and span

Explaining the difference between block and inline containers.

Containers in HTML are used to group elements together for styling or scripting purposes. The two most common generic containers are <div> and <span>.

The Core Difference

  • <div>: A block-level element. It automatically starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
  • <span>: An inline element. It does not start on a new line and only takes up as much width as necessary for its content.

Comparison Example

html
<div>Block Element</div>
<span>Inline Element</span>

Interview questions

Sign in to save

Why is nesting a <div> inside a <span> considered invalid HTML?

Nesting block-level elements (like `<div>` or `<p>`) inside inline elements (like `<span>` or `<a>`) violates the HTML specifications (except in HTML5 where anchor tags can wrap divs). Browsers will attempt to render it, but it breaks standard document parsing schemas and accessibility flow.

Practice

Identify which elements are block-level vs inline from the following list: p, a, div, img, h1, span.

Hint: p, div, and h1 are block-level. a, img, and span are inline.