【发布时间】:2017-03-27 19:18:04
【问题描述】:
我需要制作一个包含两个元素的面板标题。第一个占据了大部分空间,而第二个只占据了他需要的空间。
结构如下:
.flex-child> display: flex
.child-1 > flex-grow: 1
.child-2 > align-self: center
出于样式原因,第一个元素有一个带有white-space: nowrap 的文本,如果大于父元素则显示省略号。但是display: flex 的父级并没有将元素限制在其可用空间内。
下面的代码sn-p显示了当1)第一个元素有很多文本时元素的状态; 2) 第一个元素有合理数量的文字;和 3) 我希望元素如何出现,但我只能使用 max-width 这样的幻数。使用相同代码的小提琴:https://jsfiddle.net/mjtf4ec3/1/.
.fixed-width-parent {
margin: 1em 2em;
width: 300px;
background: #dedede;
padding: 15px;
}
.unbreakable-text {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.flex-child {
display: flex;
}
.child-1 {
flex-grow: 1;
}
.child-2 {
align-self: center;
margin-left: 5px;
}
.fancy-button {
padding: 5px;
background-color: #1a1;
border: 1px solid #080;
border-radius: 5px;
color: #fff;
}
.expectation .child-1 {
min-width: 80%;
}
.unimportant {
color: #bbb;
}
body {
font-family: sans-serif;
font-size: 14px;
}
<div class="fixed-width-parent">
<div class="flex-child">
<div class="child-1">
<div class="unbreakable-text">
<strong>Very long text NOT OK</strong>
Lorem ipsum dolor sit amet, consectetur
</div>
<div class="unimportant">Unimportant text
<br> Very unimportant</div>
</div>
<div class="child-2">
<div class="fancy-button">
Button
</div>
</div>
</div>
</div>
<div class="fixed-width-parent">
<div class="flex-child">
<div class="child-1">
<div class="unbreakable-text">
<strong>Short text OK</strong>
</div>
<div class="unimportant">Unimportant text
<br> Very unimportant</div>
</div>
<div class="child-2">
<div class="fancy-button">
Button
</div>
</div>
</div>
</div>
<div class="fixed-width-parent expectation">
<div class="flex-child">
<div class="child-1">
<div class="unbreakable-text">
<strong>EXPECTATION (without <code>max-width</code> as %)</strong> Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</div>
<div class="unimportant">Unimportant text
<br> Very unimportant</div>
</div>
<div class="child-2">
<div class="fancy-button">
Button
</div>
</div>
</div>
</div>
【问题讨论】:
-
minimal reproducible example 请在您的问题中。当您链接到 jsFiddle 时突出显示
white-space: nowrap代码绕过 SO 过滤器时,我们需要一个完整的示例。谢谢。 -
您的问题令人困惑...为什么不将空白属性更改为 'wrap' 而不是 'nowrap' jsfiddle.net/pttgas4p
-
如何在固定宽度不那么宽的父级中适应更宽的元素...回答...你不能
-
@j08691:更新了问题以使其更清晰,感谢您的指出。我不是打算绕过 SO 过滤器。 @Maxwell:我把
white-space: nowrap用于造型目的。