Home > OS >  How to separate an in between element to a new line if its content does not fit with CSS only?
How to separate an in between element to a new line if its content does not fit with CSS only?

Time:01-17

The following is more like a general example.

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

Changing element types or adding helpers in between ist possible. All texts do not wrap. No fixed width or height must be given.

How to achieve something like this with CSS only and not by changing the DOM? So how to separate out some in between element to a new line if its content does not fit? Is it possible at all?

enter image description here

Some snippet to illustrate it in more detail and to test.

.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 very very very long";
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>
<br />
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

float is the only solution here BUT you have to adjust the HTML structure (I know it's against your requirement but the below may give you some ideas)

.box {
  border:1px solid red;
  padding: 3px;
  /* to debug */
  overflow: hidden;
  resize: horizontal;
  /**/
}
.box > div {
  border: 1px solid #000;
  box-sizing: border-box;
}

.box > :first-child {
  float: left;
}
.box > :nth-child(2) {
  float: right;
}

#in-between {
  display: inline-block;
  
  /* remove the below if you want text wrap instead of ellpsis*/
  max-width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
<div >
  <div>Short dynamic text.</div>
  <div>Short dynamic text.</div>
  <div id="in-between">Possible long dynamic text Possible long text</div>
</div>

  •  Tags:  
  • css
  • Related