36. The Display Property: block, inline, inline-block
The display property is the most fundamental property affecting how an element behaves in the document flow, dictating its layout context and how it interacts with the Box Model.
1. Block-Level Elements (display: block)
Block elements take up the full available width and always start on a new line. They respect all Box Model properties (width, height, padding, margin).
- Examples:
<div>,<h1>to<h6>,<p>,<ul>,<li>.
css .my-div { display: block; /* The default for divs / width: 50%; / Respects width property / margin: 10px; / Respects margin property */ }
2. Inline Elements (display: inline)
Inline elements only take up as much width as necessary for their content. They flow along the text line and do not start on a new line.
- Examples:
<span>,<a>,<strong>,<em>. - Restrictions: Inline elements do not respect
width,height,margin-top, ormargin-bottom.
3. Inline-Block Elements (display: inline-block)
Inline-block elements combine traits of both:
- They flow side-by-side like inline elements (they don't force a new line).
- They respect
width,height, padding, and margin, just like a block element.
css .nav-item { display: inline-block; padding: 10px 15px; margin-right: 5px; /* Margin works on all sides */ }
Historical Note: inline-block was a primary layout tool before Flexbox and Grid, especially for menu navigation.