The inline
, block
, and inline-block
values for the CSS display
property control how an element is laid out on a web page. Here's a breakdown of their differences:
inline
:
- Flows horizontally: Inline elements flow horizontally within a line of text, like words in a sentence. They only take up as much horizontal space as their content requires.
- No width or height: You cannot set a fixed width or height on an inline element. The dimensions are determined by the content.
- Vertical padding and margin: While vertical padding and margins are applied, they don't affect the layout of other inline elements. They might overlap with content above or below.
- Examples:
<span>
,<a>
,<img>
,<em>
,<strong>
block
:
- Starts on a new line: Each block element starts on a new line and takes up the full width available (stretches horizontally to the edges of its containing element).
- Width and height can be set: You can explicitly set the width and height of a block element.
- Padding and margins apply: Padding and margins apply in all directions (top, right, bottom, left) and affect the layout of other elements.
- Examples:
<div>
,<p>
,<h1>
-<h6>
,<ul>
,<ol>
,<li>
,<form>
inline-block
:
- Flows like inline, but behaves like block: This is the hybrid approach.
inline-block
elements flow horizontally like inline elements, but you can set a width and height on them. - Padding and margins apply: Padding and margins apply in all directions and affect the layout of other elements.
- Best of both worlds:
inline-block
is useful for creating navigation menus, laying out images with text, or generally controlling the size and spacing of elements within a line. - Example: Imagine several
<div>
elements set todisplay: inline-block
. They would sit next to each other on the same line (like spans), but you could individually control the width and height of each<div>
.
Key Differences Summarized:
Feature | inline |
block |
inline-block |
---|---|---|---|
Flows Horizontally | Yes | No | Yes |
Takes Full Width | No | Yes | No |
Settable Width/Height | No | Yes | Yes |
Padding/Margins Affect Layout | Partially | Yes | Yes |
Example Scenario:
Imagine you want three colored boxes next to each other.
inline
: You couldn't useinline
because you can't set the width or height of the boxes.block
: Each box would stack vertically, taking up the full width.inline-block
: This is the perfect solution! The boxes would sit next to each other, and you could control their individual sizes.