Skip to main content

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 margin and padding are fully applied, creating space between the elements.

2. Internal Behavior (Like block)

  • Respects width and height: Unlike pure inline elements, inline-block elements fully respect explicitly set width and height properties.
  • Respects All Margins/Padding: All four sides of margin and padding (top, right, bottom, left) are fully applied and respected without causing visual overlap.

Best Use Cases for inline-block

  1. Navigation Menus: Before Flexbox and Grid became widespread, inline-block was the standard way to lay out horizontal navigation links.
  2. Card Grids: Creating simple, responsive layouts where cards stack vertically on small screens but flow horizontally on larger ones.
  3. 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 4px4\text{px} to 8px8\text{px}) 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.

index.html
<!-- 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:

  1. Remove Whitespace in HTML: Edit your HTML to place all inline-block tags on the same line without any spaces.
  2. Set Parent font-size: 0;: Set the font size of the parent container to 00. 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.