DaraJ
DaraJ

Reputation: 3036

Wrapping 2 lines at at time in CSS

I have thought about this and I'm not sure if it's possible with a CSS only solution, although I'm not even sure how I'd do it with JS.

Given text like the following:

123456789012345678901234567890
This is a whole bunch of words
123456789012345678901234567890
Yes it is yes it is oh yes....

And having a screen so narrow that only the first 20 chars can fit. How can I wrap the text so that it displays like this:

1234567890123456789
This is a whole bun
01234567890
ch of words
12345678901234567890
Yes it is yes it is 
1234567890
oh yes....

That is, wrapping 2 lines at a time. Typical wrapping rules will give me the wrong result:

1234567890123456789
01234567890
This is a whole bun
ch of words
1234567890123456789
01234567890
Yes it is yes it is
 oh yes....

Upvotes: 0

Views: 133

Answers (2)

Temani Afif
Temani Afif

Reputation: 272723

Placing the texts above each other and using a big line-height can approximate this:

.box {
  position: relative;
  font-size: 1.2em;
  line-height: 2.4em; /* twice the font-size*/
  padding-top: 1.2em; /* equal to font-size*/
  font-family: monospace;
  
  /* to illustrate */
  overflow: hidden;
  border: 1px solid;
  resize: horizontal;
  word-break: break-all; /* omit this to keep full words */
}

.box div {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  word-break: break-all;
}
<div class="box">
  <div>123456789012345678901234567890123456789012345678901234567890</div>
  This is a whole bunch of words Yes it is yes it is oh yes....
</div>

Upvotes: 4

Ouroborus
Ouroborus

Reputation: 16865

:root {
  --font-size: 16px;
}
div {
  position: relative;
  width: 22.5ex;
  border: 1px solid red;
  overflow: hidden;
  resize: horizontal;
}
div > pre {
  white-space: pre-wrap;
  word-break: break-all;
  vertical-align: baseline;
  margin: 0;
  font-size: var(--font-size);
  line-height: calc(var(--font-size) * 2 * 1.2);
}
div > pre:first-child {
  position: absolute;
}
div > pre:last-child {
  padding-top: calc(var(--font-size) * 1.2);
}
<div>
<pre>123456789012345678901234567890123456789012345678901234567890</pre>
<pre>This is a whole bunch of words Yes it is yes it is oh yes...</pre>
</div>

Unfortunately there's still some issues with this. There's no way to get the character width in CSS so, without javascript, you're left to guessing.

Upvotes: 1

Related Questions