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

问题描述 投票:0回答:4

我该如何创建下一个布局:

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

  • 右侧的 div 与文本内容一样宽
  • 左侧的 div 占据了父级的所有剩余宽度,并使用 text-overflow: ellipsis 在文本被剪切的位置显示“...”。

这是我认为我所知道的应该如何实施 -

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

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

.right {
  display: inline-block;
}
<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>

它应该看起来像this example

html css
4个回答
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>


2
投票

我认为使用

Flexbox
更好。您应该将
display: flex;
赋予
.parent
,将
flex:1;
赋予
.left
。这将达到你的目的,并且它也不会超出 parent 宽度。

.parent {
  width: 100%;
  height: 200px;
  display: flex;
}
.left {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  background: pink;
  flex:1;
}
.right {
  background: green;
}
<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>


0
投票

试试这个

.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;
 
}
<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>

**


0
投票

您可以根据您的要求使用

flexbox
。它非常简单,并且像任何其他
display
属性一样工作。您可以查看这个codepen链接。这100%有效。

CSS

.container {
  display: flex;
  max-width: 500px;
  border: 1px solid #ddd;
  padding: 5px;
}
.one, 
.two {
  flex-grow: 1;
  word-break: break-all;
  padding: 10px;
  color: #fff;
}
.one {
  background-color: red;
}
.two {
  background-color: blue;
}
© www.soinside.com 2019 - 2024. All rights reserved.