CSS Simplified

Share this post

Can you limit a paragraph width based on the text within?

shrutibalasa.substack.com

Can you limit a paragraph width based on the text within?

Shruti Balasa
Jan 19
3
Share this post

Can you limit a paragraph width based on the text within?

shrutibalasa.substack.com

The question is simple and it feels like the answer should be simple too. Suppose we have a short phrase in a paragraph element like this with a blue background.

Now since the p element is a block level element, it stretches full width. How would you restrict it to just the width of the text, like so?

The most common way of doing this is by setting display: inline-block to the element. Of course it works. But what if we have a span element to be displayed below it?

Setting display: inline-block to the paragraph will make the span move up :( We don’t want that.

So we cannot use display: inline-block without adding a new line or something else.

Another solution is to use the float property. But we face the same problem with floats too. We need to clear the float.

What’s the best solution?

Did you know you could simply use this CSS rule?

width: max-content; /* 🤯 */

Surprised? See it for yourself here.

Have you ever used max-content in grid layouts? Yes, the same max-content can be applied to any such property, not just in grids. Also useful for buttons like in the below screenshot.

You can use display: block along with width: max-content for the button to limit the width.

Hope you learnt something new today :)

📘 Complete Guide to CSS Flex and Grid

If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!

📨 Newsletter suggestion

I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇

Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.

Thanks for reading CSS Simplified! Subscribe for free to receive new posts and support my work.

Share this post

Can you limit a paragraph width based on the text within?

shrutibalasa.substack.com
Comments
TopNewCommunity

No posts

Ready for more?

© 2023 Shruti Balasa
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing