CSS创建一个div,当另一个兄弟div与其内容一样宽时,该div占用父级的剩余宽度?

时间:2017-08-16 11:47:34

标签: html css css3

如何创建下一个布局:

两个div共享一个共同父级的宽度。它们都在一行中显示文本内容,而 -

  • 右边的div和它的文字内容一样宽
  • 左侧的div占用父级的所有剩余宽度,并使用text-overflow:省略号来显示' ...'文本被删除的地方。

以下是我认为我应该如何实施的内容 -



.parent {
  width: 400px;
  height: 200px;
}

.left {
  display: block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: none;
}

.right {
  display: inline-block;
}

<div class='parant'>
  <div class='left'> This div should display all text content possible without line-breaking and display '...' where its being cut </div>
  <div class='right'> This div is as wide as its text content </div>
</div>
&#13;
&#13;
&#13;

它应该看起来像this example

4 个答案:

答案 0 :(得分:3)

您可以使用Flexbox,只需在父元素上设置display: flex,在右元素上设置flex-shrink: 0

.parent {
  width: 400px;
  height: 200px;
  display: flex;
}
.left {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  background: red;
}
.right {
  background: lightblue;
  flex-shrink: 0;
}
<div class='parent'>
  <div class='left'> This div should display all text content possible without line-breaking and display '...' where its being cut </div>
  <div class='right'> This div is as wide as its text content </div>
</div>

答案 1 :(得分:2)

我认为使用 Flexbox 可以做得更好。您应该将display: flex;提交给.parent,将flex:1;提交给.left。这将是你的伎俩,它也不会过度流动宽度。

&#13;
&#13;
.parent {
  width: 100%;
  height: 200px;
  display: flex;
}
.left {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  background: pink;
  flex:1;
}
.right {
  background: green;
}
&#13;
<div class='parent'>
  <div class='left'> This div should display all text content possible without line-breaking and display '...' where its being cut </div>
  <div class='right'> This div is as wide as its text content </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个

&#13;
&#13;
.parent { 
   width: 300px; 
   height: 200px; 
   overflow: hidden;
   display: flex;
}
.left {   
   white-space: nowrap; 
   text-overflow: ellipsis;  
   overflow: hidden;
  
 }
.right {
   white-space: nowrap; 
   text-overflow: ellipsis;  
   overflow: hidden;
 
}
&#13;
<div class='parent'>
  <div class='left'> This div should display all text content possible without line-breaking and display '...' where its being cut </div>
  <div class='right'> This div is as wide as its text content </div>
</div>
&#13;
&#13;
&#13;

**

答案 3 :(得分:0)

您可以根据自己的要求使用{field : { first_name : scope.model }} 。它非常简单,它可以像任何其他flexbox属性一样工作。您可以查看codepen link。这100%工作。

CSS

display