Display inline-block
The display: inline-block value is the compromise between block and inline. It is a crucial display value for creating structured layouts that need to flow horizontally, such as navigation bars, list items in a grid, or form elements.
An element set to inline-block gains the best features of both its siblings.
Key Characteristics of inline-block
1. External Behavior (Like inline)
- Flows Horizontally: The element sits on the same line as the elements before and after it. It flows left-to-right and wraps to the next line when space runs out.
- Respects Horizontal Spacing: Horizontal
marginandpaddingare fully applied, creating space between the elements.
2. Internal Behavior (Like block)
- Respects
widthandheight: Unlike pure inline elements,inline-blockelements fully respect explicitly setwidthandheightproperties. - Respects All Margins/Padding: All four sides of
marginandpadding(top,right,bottom,left) are fully applied and respected without causing visual overlap.
Best Use Cases for inline-block
- Navigation Menus: Before Flexbox and Grid became widespread,
inline-blockwas the standard way to lay out horizontal navigation links. - Card Grids: Creating simple, responsive layouts where cards stack vertically on small screens but flow horizontally on larger ones.
- Form Elements: Aligning labels, inputs, and buttons on the same line while still controlling their individual size.
The inline-block Gap
A common issue when using inline-block is the appearance of a small gap (typically to ) between elements that should be touching. This gap is caused by the white space (spaces, tabs, or new lines) between the element tags in the HTML source code.
<!-- The space/newline here creates the gap -->
<div class="item">A</div> <div class="item">B</div>
<!-- Even with no space, the line break creates the gap -->
<div class="item">C</div>
<div class="item">D</div>
Solutions to Remove the Gap
While there are multiple fixes, two common approaches are:
- Remove Whitespace in HTML: Edit your HTML to place all
inline-blocktags on the same line without any spaces. - Set Parent
font-size: 0;: Set the font size of the parent container to . Since the gap is treated as a character space, this removes it. You must then re-declare the font size on the children.
Interactive display: inline-block Demo
In the demo below, the elements flow horizontally but fully respect the set width, height, and all four margins/paddings, making them predictable building blocks.