Explain Codes LogoExplain Codes Logo

Display block without 100% width

css
responsive-design
best-practices
css-solutions
Alex KataevbyAlex Kataev·Oct 5, 2024
TLDR

To make an HTML element block-level without stretching to full width, set the CSS display property to inline-block; :

.element { display: inline-block; }

This way, elements act like blocks, but only take up content-requisite space.

Alternatively, for a "Read more" link, combine display: block;, float: left;, and clear: left; for more control:

.read-more { display: block; float: left; clear: left; }

The "Read more" link stays below the article, not affecting other elements' layout.

Principles of width control

Convert to table-style display

By choosing display: table;, an element imitates a table without going full-width:

.non-stretch-element { display: table; /* Voila, you're a table now! But keep it classy, no stretchy behavior here. */ }

A span with this setting wouldn't stretch full width, giving you a pseudo-table layout for neatly organized contents.

Width management with max-content

Setting width to max-content; ensures the element never exceeds the content's natural width:

.restricted-width-element { width: max-content; /* Like a well-mannered guest, won't take more space than needed. */ }

Remember to check browser compatibility before you invite this guest to the party!

Riding the float and clear wave

Float elements to the left and clear them for better layout flow and prevent undesired stretching.

.floated-element { float: left; /* I'm on a boat! */ } .element-below { clear: left; /* Everyone off the boat! */ }

This tip works well where you need inline blocks or news list items inline.

Inline-block flexibility

display: inline-block; allows inline placement without stretching the full breadth of the container. It's like doing yoga, primed for alignment and breathing space🧘.

Structure tactics with divs

Properly structuring divs with display: inline-block; results in a clean, maintainable layout. It's like your mom organizing your room - everything has a place, and there's a place for everything!

Float and clear for layout hygiene

Floating elements prevent unwanted stretching. But clearing is crucial to managing the flow of subsequent elements for a clean layout. It's like doing laundry: separate whites from colors to avoid a pink sock surprise!

Tactics and optimizations

Making peace with browser compatibility

Before using width: max-content;, it's best to check browser compatibility. The only unpredictable guest at your party shouldn't be your CSS!

Practice and test runs

All CSS solutions should have a trial period. Test across different browsers and devices to ensure they play well.

Exploring display realms

Dare to explore more display property values. The realms of display: table-cell; or display: flex; hide responsive design treasures you might stumble upon!