Make a flexible element the width of its text

I want to have a layout with two columns, where the left column is a kind of sidebar.

Now I want to use some text in the sidebar, which should not end.

When I do this, it causes some kind of overflow, and then using overflow:hidden hides a significant part of the text.

How to change the left column to use the width of the expanded text and the right column to use the remaining space without dropping overflow:hidden ?

 #container { display: flex; } #sidebar { border: 1px solid red; flex 1 auto; overflow: hidden; } #sidebar .column { white-space: nowrap; } #sidebar .column span { margin: 2px; padding: 2px; border: 1px solid green; display: inline-block; } #content { border: 1px solid black; flex: 1 100%; } 
 <div id="container"> <div id="sidebar"> <div class="column"> <span>Howdy Cowboy, some text is missing here</span> </div> </div> <div id="content"> Some funny content </div> </div> 

JSFIDDLE

+6
source share
1 answer

How to change the left column to use the width of the expanded text and the right column to use the remaining space without resetting overflow:hidden ?

Say that the left column will only be as wide as its contents.

So instead:

 #sidebar { flex: 1 auto; /* 1 */ overflow: hidden; border: 1px solid red; } 

Use this:

 #sidebar { flex: 0 1 auto; /* 1 */ overflow: hidden; border: 1px solid red; } 

And tell the right column to use any remaining space.

Instead of this:

 #content { flex: 1 100%; /* 2 */ border: 1px solid black; } 

Use this:

 #content { flex: 1; /* 2 */ border: 1px solid black; } 

revised violin

Notes:

  1. flex: 1 auto is short for flex-grow: 1 (defined), flex-shrink: 1 (default) and flex-basis: auto (defined). Switch to flex-grow: 0 since you do not want the box to expand beyond the content.

    By the way, flex-grow: 0 , flex-shrink: 1 and flex-basis: auto are all default values . Therefore, you can omit the flex rule and get the same result.

    Please note that your code will not work in any case, because you have a syntax error (missing : .

  2. flex-basis: 100% will cause the element to expand as much as possible across the width of the container, even if it invaded the space of the sidebar. Just use flex: 1 (same as flex-grow: 1 , flex-shrink: 1 , flex-basis: 0 ), which says that the element consumes only free space.

+6
source

Source: https://habr.com/ru/post/1011960/


All Articles