Explain Codes LogoExplain Codes Logo

Css to line break before/after a particular inline-block item

html
responsive-design
css-tricks
flexbox
Anton ShumikhinbyAnton Shumikhin·Aug 27, 2024
TLDR

For a fast break after an inline element, use the ::after pseudoelement with content: "\\A" and white-space: pre;:

.break-after::after { content: "\\A"; white-space: pre; }

To break before the element, simply replace ::after with ::before. Apply .break-after to the elements you want to break.

Why it's not that simple with inline-block elements

Sadly, dealing with inline-block elements isn't as simple. Let's break it down.

After the quick fix: understand the underlying mechanics

The limitation with inline-block

That method won't work with inline-block. Because inline-block respects the flow, its styling behavior differs.

Use display: block for a practical alternative

Here's an alternative solution with display: block:

.break-before-inline-block { display: block; content: ''; }

When in doubt, go old school: HTML's <br>

If all else fails and you have control over the HTML, you can manually insert a <br> before or after the inline-block element.

Make the most out of the pseudo-elements

To space out multiple inline-block elements, use clear: both on a block-level pseudo-element to create a gap.

.break-after-inline-block { clear: both; display: block; }

Creating a three-column layout, the modern way

You want a three-column layout without floats or fixed widths, right? You're likely aiming for a dynamic, adaptable design. Here's how:

Keeping it semantic with <ul>

Utilize nested <ul> lists for semantic fidelity:

<ul class="three-columns"> <li><ul><li>Column 1 Content</li></ul></li> <li><ul><li>Column 2 Content</li></ul></li> <li><ul><li>Column 3 Content</li></ul></li> </ul>

CSS does the rest

Here's the CSS for fluid columns:

.three-columns > li { display: inline-block; width: 33.33%; } .three-columns ul { width: 100%; }

Your columns will now share the viewport width equally, on any screen size. No floats, no fixed-width!

Meet the curveballs with these back pocket CSS tricks

A clearfix for legacy code

Even in avoiding floats, the clearfix technique is necessary to avoid unwanted layout behavior:

/* I ain't afraid of no floats */ .group::after { content: ""; display: table; clear: both; }

Flexbox for the future

For newer projects or updating old ones, flexbox is a stellar choice!

.flex-container { display: flex; flex-wrap: wrap; } /* Flexbox: Making layouts snappy since 2009 */