Explain Codes LogoExplain Codes Logo

How do you make div elements display inline?

html
responsive-design
css
layout
Nikita BarsukovbyNikita Barsukov·Jan 11, 2025
TLDR

Make div elements display inline by applying display: inline;. This removes block-level features. Alternatively, you can use display: inline-block; to retain block properties and align them in a line.

Use inline: Has no width/height control. Use inline-block: Width and height are obeyed.

.div-inline { display: inline; /* "I'm going on a diet, less block!" */ } .div-inline-block { display: inline-block; /* "Block's my life, but I also want a buddy!" */ }
<div class="div-inline">Inline div.</div> <div class="div-inline-block">Inline-block div.</div>

Consider display: flex; for modern, flexible inline layouts.

Alternatives to display: inline and inline-block

Use <span> to go inline

<span> is inherently an inline element. Useful when marking up short phrases within a text.

<p>A text block with <span>inline content</span> inside.</p>

Using float: left; as Plan B

No display: inline;? No problem! Try float: left; for inline displays. It's like a survival tool - old but still works.

.div-float { float: left; /* "Going left and never coming back!" */ }

Note: Don't forget to clear: both; on subsequent elements to avoid haunted layouts.

The white space "bug" with inline-blocks

White spaces in HTML can create unwanted gaps between inline-blocks. Either remove the spaces or pull off a magic trick with font-size: 0; on the parent.

Flexbox for future-proof layouts

Flexbox allows retentive control over alignment, order and sizes of boxes. The cool kid in the block model class.

.container { display: flex; /* "Flexin', not stressin'" */ }

Enhancements around (inline | inline-block)

Visualising borders and margins

Outline your divs with border styles. Visual aids for developing and debugging layouts!

Intentional line breaks with <br/>

Sometimes you may need line breaks in an inline layout. Use <br/> for that neat break-up.

Using <pre> to keep the whitespaces

The <pre> tag preserves initial content formatting. Keep your spaces and minds open!

The subtle art of vertical alignment

Dealing with capricious vertical alignment in inline elements? Use vertical-align to normalize things and regain control in inline-land.