Skip to main content

Inline-Block Display

The display: inline-block; value in CSS is a hybrid between display: inline; and display: block;. It allows elements to maintain an inline-level context while accepting block-level styling. This is particularly useful for creating layouts where you want elements to sit next to each other horizontally but still be able to specify their dimensions, which is not possible with pure inline elements.

Characteristics

  1. Inline Context: Like inline elements, inline-block elements sit next to each other horizontally and do not force a new line before or after them.

  2. Block Styling: Unlike inline elements, you can set the width and height of inline-block elements. They also respect padding, margin, and border settings in both vertical and horizontal directions.

  3. Box Model: The full box model applies, allowing you to control margin, border, padding, and content area, similar to block-level elements.

  4. Vertical Alignment: By default, inline-block elements are aligned along the baseline, similar to inline elements. You can control this using the vertical-align property.

  5. Whitespace Sensitivity: Like inline elements, inline-block elements are sensitive to whitespace in the HTML, which can result in unexpected spacing between elements.

Example I: Basic Usage

HTML:

<div class="inline-block-element">Element 1</div>
<div class="inline-block-element">Element 2</div>

CSS:

.inline-block-element {
display: inline-block;
}

Example II: Setting Dimensions

CSS:

.inline-block-element {
display: inline-block;
width: 200px;
height: 100px;
}

Example III: Vertical Alignment

CSS:

.inline-block-element {
display: inline-block;
vertical-align: top;
}

Example IV: Handling Whitespace

HTML:

<div class="inline-block-element">Element 1</div><!--
--><div class="inline-block-element">Element 2</div>

CSS:

.inline-block-element {
display: inline-block;
}

Best Practices

  1. Use for Grids and Columns: inline-block is useful for creating simple grid or column layouts without using Flexbox or Grid.

  2. Control Whitespace: Be aware of the whitespace issue and control it either by removing spaces in the HTML or using CSS to negate the spacing.

  3. Specify Vertical Alignment: If you have inline-block elements of varying heights, make sure to specify the vertical-align property to control their alignment.

  4. Use for Inline Elements with Dimensions: If you need an inline-level element that also needs to have set dimensions, inline-block is the way to go.