Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I align the text that didn't fit the first line to right in CSS, like they do in poetry?

Tags:

html

css

I'm adding some poetry to my website. The problem is, when the screen size gets smaller, lines of the poem break. I want to show the part of the line that comes after the line break like they do in poetry books, when the verse doesn't fit the page width. Here's an example:

The quick brown fox jumps over the
                           lazy dog

The first line is aligned to left, the second however, is aligned to right. (This will only happen in small screens, of course.)

Is there any way to do this that is repeatable? This is not a one-time thing; I'm trying to create a standard with classes.

like image 594
bedirhangn Avatar asked Nov 10 '20 14:11

bedirhangn


2 Answers

Use text-align-last

.box {
  width: 350px;
  border: 1px solid #000;
  resize:horizontal;
  overflow:auto;
}
.box * {
  /*text-align:justify; uncomment this to see the justify effect, not bad too */
  text-align-last: right;
  display:inline-block;
}
<div class="box">
  <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div><br>
  <div>Ut enim ad minim veniam, quis nostrud exercitation ullamco.</div>
</div>
like image 117
Temani Afif Avatar answered Sep 23 '22 14:09

Temani Afif


There is a CSS pseudo-element for selecting the first line of text that you could use here:

::first-line

Update: Despite the selector being supported in all major browsers it appears that several browsers don't allow text-align to be applied to this selector. So this is not a reliable cross-browser solution (yet?), I will leave it here in case it's useful to anyone or becomes valid in the future.

#wrapper {
  display: block;
  width: 350px;
  height: auto;
  border: 1px solid #000;
}
#wrapper span {
  display: block;
  text-align: right;
}
#wrapper span::first-line {
  text-align: left;
}
<div id="wrapper">
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
  <span>Ut enim ad minim veniam, quis nostrud exercitation ullamco.</span>
  <span>Duis aute irure dolor in reprehenderit in voluptate velit esse.</span>
</div>

This does assume you will have at most 1 line of overflow (all overflowing lines will be right aligned) but at that point it will look a little strange no matter the styling.

like image 32
DBS Avatar answered Sep 22 '22 14:09

DBS