Line height doesn't affect first line in contenteditable

1.8k views Asked by At

Consider the following HTML:

<div class="content" contenteditable="true">
rrr<br>
ttt
</div>

& CSS:

.content {
line-height: 35px;
}

What you get is the line height affecting only second line and below. What bothers me is that the caret's height is affected by the line height therefore it is significantly shorter in the first line then on the second line.

Use this Fiddle to see it in action. Place the caret in the first line and in the second line and observe the caret in each of them. Notice it's height is different due to the line-height.

I cannot allow inner wrappers for each line in the main contenteditable element.

When trying to use div::first-line and use line-height in that css rule it doesn't affect it, although other properties like background-color do.

Is there a possible way to affect the first line as well? I prefer a css-only solution, but if there is no choice, Js will do as well.

2

There are 2 answers

3
light On BEST ANSWER

Despite what is mentioned in the other answer(s), it is not really an issue with <br>. The actual issue is with Chrome - specifically how it processes text on line-height greater than its own height. This Chrome line-height issue is actually a longstanding source of irritation for many of us doing CSS. The caret always span the entire line-height, and the text is not vertically middle of the line-height. To make it worse, they treat the first line different from the rest other lines :(

The suggestion on <br> is a hack to mask the problem, but it only works if you are going to manually input line breaks in the text area. Just to demonstrate that the br hack method won't work for regular textareas / contenteditable regions with naturally occurring wrapping text: http://jsfiddle.net/8ao367gz/1/

The Bad News: There is no real solution to it as yet. The general consensus is to find a way around your design and don't set line-height to anything other than normal or 1. If you must use line-height in the design, either live with the weird-looking bottom-aligned caret spanning the entire line-height on Chrome, or tell your users to use another browser without this issue (like Firefox). Or we can all continually complain and submit bug reports to Chrome and pray that they "fix" this. I highly doubt so, since I don't think they consider this a bug; and even if they do, probably a very low priority one.

2
boszlo On

Walkaround (this won't break expected behaviour as mentioned in the comment below):

br {
  content: " ";
  visibility: hidden;
  display: block;
}