Inline Display
The display: inline;
value in CSS is another fundamental display setting that controls how an element behaves within the layout. Unlike block-level elements, inline elements do not start on a new line and only take up as much width as their content requires.
Characteristics
No Line Breaks: Inline elements do not start on a new line and will not force a new line after them. They flow within the text and other inline elements.
Width and Height: Unlike block-level elements, setting the
width
andheight
properties on inline elements will not have any effect. The dimensions are determined by the content.Horizontal Margins and Padding: You can apply left and right margins and padding, but top and bottom margins and padding won't affect the element's dimensions.
No Full-Width: Inline elements do not take the full width of their parent container; they only take up as much space as their content requires.
Vertical Alignment: You can use the
vertical-align
property to control the vertical positioning of inline elements relative to their baseline.Box Model: The box model is limited for inline elements. While you can still apply
border
andpadding
, themargin
,width
, andheight
properties behave differently compared to block-level elements.
Example I: Basic Usage
HTML:
<span class="inline-element">This is an inline element.</span>
CSS:
.inline-element {
display: inline;
}
Example II: Adding Border and Padding
CSS:
.inline-element {
display: inline;
border: 1px solid #ccc;
padding: 5px;
}
Example III: Horizontal Margin
CSS:
.inline-element {
display: inline;
margin-left: 10px;
margin-right: 10px;
}
Example IV: Vertical Alignment
CSS:
.inline-element {
display: inline;
vertical-align: top;
}
Best Practices
Appropriate Use: Use
display: inline;
for elements that should be part of the text flow, like<span>
,<a>
, or<strong>
.Avoid Width and Height: Since
width
andheight
have no effect, avoid setting these properties on inline elements.Use Inline-Block for Dimensions: If you need an inline element with dimensions, consider using
display: inline-block;
.Be Mindful of Whitespace: Whitespace in HTML can affect the rendering of inline elements. Make sure to account for this in your layout.