Skip to content Skip to sidebar Skip to footer

Make Flex Item Be The Width Of Its Text

I want to have a layout with two columns, where the left column is some kind of sidebar. Now I want to use some text in the sidebar that shouldn't wrap. When I do so it causes so

Solution 1:

How can I modify the left column to use the width of the unwrapped text and the right column to use the remaining space without dropping overflow:hidden?

Tell the left column to be only as wide as its content.

So instead of this:

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

Use this:

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

And tell the right column to consume any remaining space.

Instead of this:

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

Use this:

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

revised fiddle

Notes:

  1. flex: 1 auto is shorthand for flex-grow: 1 (defined), flex-shrink: 1 (by default) and flex-basis: auto (defined). Switch to flex-grow: 0 since you don't want the box to expand beyond the content.

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

    Note that your code won't work in any case because you have a syntax error (a missing :).

  2. flex-basis: 100% will force the item to expand as much as it can across the width of the container, even intruding into the sidebar space if it can. Just use flex: 1 (same as flex-grow: 1, flex-shrink: 1, flex-basis: 0), which tells the item to consume only free space.

Post a Comment for "Make Flex Item Be The Width Of Its Text"