1

I have a layout with a menu column which is allowed to stretch between two widths by min-width and max-width:

#menu {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  max-width: 350px;
}

There are link placed to this container programatically, which can cause it to grow if their text is too long or stay at the min-width if it isn't. If the text of any one link is too long, the menu will stay at 350px and the links text will instead break.

This is all fine. There is also a paragraph following the links with static text in it. The text always works out to be so long it stretches the container to its maximal width and then starts breaking lines.

I am curious if I can instruct the CSS layout engine to make this paragraph break ASAP instead of contributing to the width of it.

This way the links would cause the container to stay shrunk or grow to its allowed extent as needed, but the paragraph would only ever span to the effective width of the menu and then start breaking lines, never pushing the menu to grow wider, only the links could.

I am struggling to come up with any CSS property that would affect this and I did think about wrapping up the paragraph in a wrapper div figuring I would first have the wrapper div be laid out, then its children which would span its entire width, but I would still need to come up with a way to make the wrapper div span the effective with of the menu container without actually pushing it further.

Is there a way to have an element which behaves like a block in that it spans the parent's width but doesn't cause the parent to grow if its contents' width is greater than the one of the parent at the same time?

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125

1 Answers1

2

Here is a trick using min-width/width. Basically you tell the browser to have a width equal to 0 then a min-width:100% and the 100% will be the width already defined by the other content (the link in your case)

#menu {
  display: inline-flex;
  flex-direction: column;
  min-width: 150px;
  max-width: 300px;
  border:1px solid;
}

p {
 width:0;
 min-width:100%;
}
<div id="menu">
<a href=""> a link here </a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin sed mauris non lacus congue semper. Maecenas pulvinar, quam d,</p>
</div>
<br>
<div id="menu">
<a href=""> a very long long looooooooooong link here </a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin sed mauris non lacus congue semper. Maecenas pulvinar, quam d,</p>
</div>
<br>
<div id="menu">
<a href=""> a veeeeeeeeeeeeeeery long long long looooooooooong link here </a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin sed mauris non lacus congue semper. Maecenas pulvinar, quam d,</p>
</div>

Similar question: How to match width of text to width of dynamically sized image?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415