如果中間元素的內容不適合只使用 CSS,如何將其分隔為新行?
P粉691461301
P粉691461301 2024-02-26 22:10:44
0
1
401

以下更像是一個一般範例。

<div>
  <div>Short dynamic text.</div>
  <div id="in-between">Possible long dynamic text...</div>
  <div>Short dynamic text.</div>
</div>

可以事先更改元素順序或類型或在其間新增幫助程序。所有文字均不換行。不必給出固定的寬度或高度。

如何只使用 CSS 而不是透過更改 DOM 來實現這樣的效果?那麼,如果內容不適合,如何將中間元素分離到新行呢?這可能嗎?

有些片段可以更詳細地說明並進行測試。

.example {
  display: flex;
  flex-wrap: wrap;
  column-gap: 0.5rem;
  justify-content: space-between;
}

.example .separate {
  flex-grow: 1;
}

.example .long-b {
  order: 1; /* this should happen by some magic */
}

/* do not change below */

.container {
  border: 0.5rem solid black;
  background: blue;
}

.element {
 border: 0.5rem solid yellow;
 padding: 0.5rem;
 color: white;
 white-space: nowrap;
 overflow: hidden;
 text-overflow: ellipsis;
}

.short-a:before {
  content: "only three words";
}

.short-b:before {
 content: "flag";
}

.short-c:before {
  content: "i love stackoverflow";
}

.short-d:before {
 content: "attribute";
}

.long-a:before {
  content: "i am not that long";
}

.long-b:before {
  content: "i am very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long";
}
<div class="container example">
  <div class="element short-a"></div>
  <div class="element separate long-a"></div>
  <div class="element short-b"></div>
</div>
<br />
<div class="container example">
  <div class="element short-c"></div>
  <div class="element separate long-b"></div>
  <div class="element short-d"></div>
</div>

目前的答案很有幫助並且可以接受。然而,是否有(或將會有)其他不利用浮動的方法?

P粉691461301
P粉691461301

全部回覆(1)
P粉147045274

float 是這裡唯一的解決方案,但你必須調整 HTML 結構(我知道這違反了你的要求,但下面的內容可能會給你一些想法)

.box {
  border:1px solid red;
  padding: 3px;
  /* to debug */
  overflow: hidden;
  resize: horizo​​ntal;
  /**/
}
.box > div {
  邊框:1px 實心#000;
  框大小:邊框框;
}

.box > :first-child {
  向左飄浮;
}
.box > :nth-child(2) {
  浮動:右;
}

#中間{
  顯示:內聯塊;
  
  /* 如果您想要文字換行而不是省略號,請刪除以下內容*/
  max-width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
Short dynamic text.
Short dynamic text.
Possible long dynamic text Possible long text
###
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板