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
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.Block Styling: Unlike inline elements, you can set the
width
andheight
ofinline-block
elements. They also respect padding, margin, and border settings in both vertical and horizontal directions.Box Model: The full box model applies, allowing you to control
margin
,border
,padding
, andcontent
area, similar to block-level elements.Vertical Alignment: By default,
inline-block
elements are aligned along the baseline, similar to inline elements. You can control this using thevertical-align
property.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
Use for Grids and Columns:
inline-block
is useful for creating simple grid or column layouts without using Flexbox or Grid.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.
Specify Vertical Alignment: If you have
inline-block
elements of varying heights, make sure to specify thevertical-align
property to control their alignment.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.