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";
});