[英]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 some kind of overflow and then using overflow:hidden
hides a good part of the text. 当我这样做它会导致某种溢出然后使用
overflow:hidden
隐藏文本的很大一部分。
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
? 如何修改左列以使用未包装文本的宽度和右列来使用剩余空间而不丢弃
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>
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
?如何修改左列以使用未包装文本的宽度和右列来使用剩余空间而不丢弃
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: 0 1 auto; /* 1 */
overflow: hidden;
border: 1px solid red;
}
And tell the right column to consume 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;
}
Notes: 笔记:
flex: 1 auto
is shorthand for flex-grow: 1
(defined), flex-shrink: 1
(by default) and flex-basis: auto
(defined). flex: 1 auto
是flex-grow: 1
简写flex-grow: 1
(已定义), flex-shrink: 1
(默认情况下)和flex-basis: auto
(已定义)。 Switch to flex-grow: 0
since you don't want the box to expand beyond the content. 切换到
flex-grow: 0
因为您不希望框扩展到内容之外。
Incidentally, flex-grow: 0
, flex-shrink: 1
and flex-basis: auto
are all default values . 顺便提一下,
flex-grow: 0
, flex-shrink: 1
和flex-basis: auto
都是默认值 。 Hence, you can omit the flex
rule and get the same result. 因此,您可以省略
flex
规则并获得相同的结果。
Note that your code won't work in any case because you have a syntax error (a missing :
) . 请注意,您的代码将不会在任何情况下工作,因为你有一个语法错误(缺少
:
)。
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. flex-basis: 100%
将强制项目在容器的宽度上尽可能多地扩展,如果可以的话甚至会侵入侧边栏空间。 Just use flex: 1
(same as flex-grow: 1
, flex-shrink: 1
, flex-basis: 0
), which tells the item to consume only free space. 只需使用
flex: 1
(与flex-grow: 1
, flex-shrink: 1
, flex-basis: 0
),它告诉项目只消耗空闲空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.