I have <div>
elements that may contain one or several <br/>
, i.e., hard line breaks. I would like the text of the new line after each <br/>
to be indented, but the first line of the <div>
should not be indented.
I first tried div { text-indent: 2rem each-line; }
. This indents the text after each <br/>
, but it also indents the first line of the <div>
. So I tried to remove the indentation of the first line with div:first-line { text-indent: 0rem; }
, but this does not work, apparently because text-indent
is not an allowed property on the :first-line
pseudo-element. Neither can I use a negative margin
or padding
on the :first-line
pseudo-element, it seems. Is there a way to achieve what I want to achieve?
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam placerat metus turpis, et auctor eros porttitor sed.
<br/>Sed ornare eget metus in interdum. Nulla ut orci eget eros ullamcorper semper.
<br/>Aliquam fringilla urna lectus, ac vestibulum diam sodales eget.
</div>
So, in this example, "Sed ornare" and "Aliquam fringilla" should be indented, but not "Lorem ipsum". Here is the CSS I tried:
div { text-indent: 2rem each-line; }
div:first-line { text-indent: 0rem; }
Here is a picture of what I am trying to achieve:
3
Answers
You can use JavaScript to wrap each line after
in a and then apply the indentation specifically to those spans.
A hacky idea using negative margin but only available on Firefox due to the support of
each-line
Well, this is something you cannot do reliably with your current HTML structure. I tried to retain your document structure (
<div> text <br> more text <br> etc. </div>
), but nothing works well, as the<br>
element only seems to respond under certain conditions, like settingdisplay: none
to remove the line breaks ormargin
.Furthermore, the MDN doc about the Line Break element itself also notes that there is little to do to style it:
What you could do instead, is wrapping the paragraphs in
<p>
tags, like this:And then apply a style to
p
: