0

I would like to center both horizontally and vertically a <p></p> that could consist of one or more lines, in a <div></div>. Only the parent's width and height are known. Note: I refer to the div as parent, and the p as child.

I've seen here and on other sites, that in order to do vertical centering, the best way would be by using display: table on the parent element and display: table-cell combined with vertical-align: middle on the child.

However, I need the div's style.top and style.left to be overwritten later by some javascript, to make it move. By using the table trick, it somehow prevents me from moving the parent, at least this way. Note that the child must stay centered when the div moves.

TL;DR:

How to center text in a div, and then still be able to move the div?

My html's body:

<div id="target">
    <p>Centered?</p>
</div>

My CSS

    div {
        outline: 1px solid white;
        background-color: #FF9F00;
        position: absolute;
        top: 0px;
        left: 0px;
        width: 200px;
        height: 200px;
        
        // how to center its child?
    }
    p {  
        font-family: Arial;
    }

My javascript way of moving:

var target = document.getElementById("target");
target.addEventListener('mousemove', function (event) {
    target.style.left = event.x + "px";
    target.style.top = event.y + "px";
});
Sho
  • 189
  • 1
  • 8

2 Answers2

2

It works if parent <div> is display: table-cell:

div {
  width: 300px;
  height: 150px;
  border: 1px solid red;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

p {
  border: 1px solid green;;
  display: inline-block;
}
<div>
  <p>lorem ipsum bla bla blah</p>
</div>
Yukulélé
  • 11,464
  • 8
  • 52
  • 76
  • Nice answer, I unfortunately can't get it to work with the rest of my code. Still upvoted though. That's my fault :/ – Sho Aug 29 '20 at 15:32
2

How about use flexbox?

div {
  display:flex;
  flex-direction:column;
  justify-content: center;
  text-align:center;
}

<div><p>I want this paragraph to be at the center, but it's not.</p></div>
toyseed
  • 89
  • 6
  • Ahah, how embarassing, it worked nearly first-try. Big thank you for the feedback. I'll still provide my code, and test other answers. I'll accept yours once I finished trying others. – Sho Aug 29 '20 at 15:26