当第一个左侧元素过长时,将右对齐的元素向下移动。

4

enter image description here

我想实现这样的效果,当粉色部分过长时,褐色部分会被推下来,而粉色部分根据其文本内容动态调整大小。
我只能用JavaScript和两个模板来实现这一点,如果粉色长度超过X,则使用第二个模板,但我想知道是否有办法仅使用CSS实现这一点?
我尝试过使用grid auto-fill/auto-fit with minmax、float、flex with wrap等方法,但是无法得到所需的结果。

.parent {
  width: 170px;
}

.flex {
  display: flex;
 }

div {
  outline: 2px solid rgba(255, 0,0, 0.3);
}
<div>
  <p>scenario A</p>
  <div class="parent flex">
    <div>
      <div class="one">A short title</div>
      <div class="three">Some text here</div>
      <div class="three">some more text</div>
    </div>
    <div>
      <button>A button</button>
    </div>
  </div>
</div>

<div>
  <p>scenario B</p>
  <div class="parent">
      <div class="one">Testing a very long title</div>
      <div class="flex">
        
      <div>
        <div class="three">Some text here</div>
        <div class="three">some more text</div>
      </div>
      <div>
        <button>A button</button>
      </div>
      </div>
  </div>
</div>

<p>can a component achieve both a and b with only css?


无法使用CSS-Grid或flexbox实现。 - Paulie_D
CSS能实现吗? - Kareem Kamal
可能需要使用 float,但这取决于你的 HTML 结构。 - Paulie_D
1个回答

1

我找到了一个解决方案,它要求第一行具有固定的高度,右侧按钮在需要时会发生溢出。

在等待一段时间以确保没有更好的解决方案之前,请接受我的解决方案。

.container {
  width: 300px;
  display: flex;
  gap: 10px;
  padding: 16px;
  font-size: 14px;
  font-family: Arial;
}

.text {
  flex: 1;
  min-width: 0;
}

.first-row {
  height: 22px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: 8px;
}

.image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #444;
}

.title {
  flex-grow: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
<h2>Long title</h2>
<div class="container">
  <div class="image"></div>
  <div class="text">
    <div class="first-row">
      <div class="title">Test title test title test title</div>
      <button>Visit store</button>
    </div>
    <div class="three">in the stores</div>
    <div class="three">sponsored</div>
  </div>
</div>

<h2>Short title</h2>
<div class="container">
  <div class="image"></div>
  <div class="text">
    <div class="first-row">
      <div class="title">Short title</div>
      <button>Visit place</button>
    </div>
    <div class="three">in the stores</div>
    <div class="three">sponsored</div>
  </div>
</div>

<h2>Very long title</h2>
<div class="container">
  <div class="image"></div>
  <div class="text">
    <div class="first-row">
      <div class="title">Test title test titleTest title test titleTest title test title</div>
      <button>Visit place</button>
    </div>
    <div class="three">in the stores</div>
    <div class="three">sponsored</div>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接