Reputation: 66375
Tested on OSX Chrome 45, align-items: center;
is working for content, but if you click into the empty editable below, the caret position is not centered until you start typing.
Is the only way to fix this with top/bottom balanced padding or is there a way of getting this to work without pixel shifting? Thanks
[contenteditable="true"] {
border: 1px solid #ddd;
display: flex;
align-items: center;
min-height: 46px;
}
[contenteditable="true"]:focus {
outline: none;
}
<div contenteditable="true"></div>
<div contenteditable="true">content is centered, but caret isn't</div>
Upvotes: 14
Views: 2082
Reputation: 1
In my opinion you should use padding instead of min-height and line-height. If it's not important to fix the height of that div. Because of padding it also looks clean.
[contenteditable="true"] {
border: 1px solid #ddd;
display: flex;
align-items: center;
padding: 15px;
}
Upvotes: 0
Reputation: 738
To achieve this effect the element's line-height has to be set to the same pixel value of the element's height. Then on :focus you can change it to a normal line-height. See the snippet below.
[contenteditable="true"] {
border: 1px solid #ddd;
display: flex;
align-items: center;
min-height: 46px;
line-height:46px;
}
[contenteditable="true"]:focus {
outline: none;
}
[contenteditable="true"]:focus:not(:empty) {
line-height:normal;
}
<div contenteditable="true"></div>
<div contenteditable="true">content is centered, but caret isn't</div>
Upvotes: 1
Reputation: 5151
just put line-height: 150%
for your contenteditable div
but if you want to set font-size
, you should Note that you should compute line-height
in proportion with font-size
to make the caret vertically center
Upvotes: 0
Reputation: 158
As James Donnelly said in the comment, you can try adding line-height to your rules, eg:
[contenteditable="true"] {
border: 1px solid #ddd;
display: flex;
align-items: center;
min-height: 46px;
line-height: 46px;
}
However I'd actually probably go with padding
instead. Adding the min-height
to your contenteditable
element is what's causing the issues between the cursor and the inputted value. Take away the min-height
, and the problem is solved. Then your problem becomes "How do I add an even amount of space around this contenteditable
element?" - and that's exactly what padding is for :)
So perhaps something more like:
[contenteditable="true"] {
border: 1px solid #ddd;
display: flex;
align-items: center;
padding: 15px 0;
}
Depends on what exactly you're trying to implement though, and whether you really need to fix the height of the div.
Upvotes: 1