display: block vs inline vs inline-block in CSS
28 block, inline and inline-block
fairGive three identical spans the same width and padding, and change only display. Watch which of them takes any notice.
Stuck? Three hints, smallest first
- 1. An inline box ignores
widthandheightcompletely. - 2.
inline-blocksits in the line like text but accepts a box: width, height and vertical padding all apply. - 3.
blockstarts on a new line and fills the available width unless you constrain it.
<p>Before them.
<span class="chip a">inline</span>
<span class="chip b">inline-block</span>
<span class="chip c">block</span>
After them.</p>
.chip {
width: 130px; /* the same request for all three */
padding: 10px;
background: #eef1fd;
border: 1px solid #3055d8;
border-radius: 6px;
font-size: 0.85rem;
}
.a { display: inline; } /* width and vertical padding do not apply */
.b { display: inline-block; } /* stays in the line, but takes the box */
.c { display: block; } /* breaks the line, takes the box */
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// Which rule asks for a width, and which display value will honour it.
const ruleFor = (cls) => (new RegExp('\\.' + cls + '\\s*\\{([^}]*)\\}').exec(css) || [, ''])[1];
test('all three chips share one rule that asks for a width', /\.chip\s*\{[^}]*width:\s*130px/.test(css), true);
test('the first is inline', /display:\s*inline;/.test(ruleFor('a')), true);
test('the second is inline-block', /display:\s*inline-block/.test(ruleFor('b')), true);
test('the third is block', /display:\s*block/.test(ruleFor('c')), true);
test('none of them overrides the width, so only display differs', ['a', 'b', 'c'].some((c) => /width/.test(ruleFor(c))), false);
test('three spans, which are inline elements to begin with', countTag(html, 'span'), 3);
test('nothing is floated to fake the difference', /float:/.test(css), false);
test('and nothing is absolutely positioned either', /position:\s*absolute/.test(css), false);
Output
The assertions can only prove that one rule asks for a width and that the three display values differ — whether the width is honoured is a rendering question, so the preview is the evidence there. What you should see: the first chip ignores the 130px entirely and its top and bottom padding spills over the lines above and below without pushing them apart, because an inline box does not reserve vertical space. inline-block is the middle ground people actually want, and block takes the whole line.