简体   繁体   English

CSS 空白 nowrap 扩展 flexbox 的子宽度

[英]CSS white-space nowrap expand flexbox's child width

I'm learning CSS and I'm having a problem with text-overflow.我正在学习 CSS,但遇到了文本溢出问题。 I have a flex-box with two child.我有一个带两个孩子的弹性盒。 I want child 2 fit into its parent and the text-content will be cut if it too long.我希望孩子 2 适合其父级,如果文本内容太长,则会被剪切。 But when I add white-space: nowrap to text then child-2 width is expanded.但是当我添加white-space: nowrap到 text 然后 child-2 宽度被扩展。 What did I do wrong here ?我在这里做错了什么?

 .parent { display: flex; flex-wrap: nowrap; max-width: 200px; margin-right: 20px; margin-bottom: 20px; padding: 15px; border: 1px solid black; } .child-1 { white-space: nowrap; border: 1px solid black; margin-right: 20px; } .text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border: 1px solid red; }
 <div class="parent"> <div class="child-1">This is child 1</div> <div class="child-2"> <div class="text">A really long long long long text</div> <div class="text">Another really long long long long text</div> </div> </div>

That's what white-space: nowrap does - it stops the text from breaking at white space and wrapping to a new line.这就是white-space: nowrap所做的 - 它阻止文本在空白处中断并换行到新行。

Your .parent is set at a max-width: 200px so child-2 it cannot grow to to fit the longer text, and the single line is too long to fit into the space beside child-1, so it has to extend outside the parent - there is nowhere else for it to go.您的.parent设置为 max-width: 200px,因此 child-2 无法适应更长的文本,并且单行太长而无法放入 child-1 旁边的空间,因此它必须延伸到父母 - 它无处可去。

I presume what you want to do is hide the part of the text that is extending out from the parent?我想你想要做的是隐藏从父级延伸出来的文本部分?

To do that you can use overflow to hide any content that extends outside of the child-2 div like this:为此,您可以使用overflow来隐藏扩展到 child-2 div 之外的任何内容,如下所示:

.child-2 { overflow:hidden; }

See more about the overflow property here: Mozilla MDN Web Docs在此处查看有关溢出属性的更多信息: Mozilla MDN Web Docs

Example hiding the overflow:隐藏溢出的示例:

 .parent { display: flex; flex-wrap: nowrap; max-width: 200px; margin-right: 20px; margin-bottom: 20px; padding: 15px; border: 1px solid black; } .child-2{ overflow:hidden; } .child-1 { white-space: nowrap; border: 1px solid black; margin-right: 20px; } .text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border: 1px solid red; }
 <div class="parent"> <div class="child-1">This is child 1</div> <div class="child-2"> <div class="text">A really long long long long text</div> <div class="text">Another really long long long long text</div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM