Initialise the vertical alignment of contenteditable div cursor with css

Viewed 784

I have the following:

  #container {
    background-color: #ddd;
    width:150px;
    height: 150px;
    display: grid;
    vertical-align: middle; text-align: center;
    align-items: center;
  }
  #container:focus {
      align-items: center;
      vertical-align: middle; 
      text-align: center;
  }
<div id='container' contenteditable="true">
</div>

I'd like to have the cursor initialise in the center of the div container. At present, it starts at the top (Chrome) or bottom (Firefox). It centralises as soon as I start typing.

How do I initialise the vertical alignment of contenteditable div cursor with css?

2 Answers

Use display:table-cell;, it should work better than grid (seems to work only with Chrome)

#container {
  background-color: #ddd;
  width: 150px;
  height: 150px;
  text-align:center;
  display:table-cell;
  vertical-align:middle;
}
<div id='container' contenteditable="true">
</div>

A hacky idea to make it work with Firefox where you need the div to be empty:

#container {
  background-color: #ddd;
  width: 150px;
  height: 150px;
  text-align:center;
  display:table-cell;
  vertical-align:middle;
}

#container:empty {
  line-height:150px;
  padding-left:75px;
  box-sizing:border-box;
  text-align:left;
}
<div id='container' contenteditable="true"></div>

This solution is very short.

*:focus {
    outline: none;
}

.div{
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    width: 300px;
    height: 300px;
    background: orange;
}
.div:empty{
    line-height:300px;
}
<div class="div" placeholder="Type something" contenteditable></div>

Related