Derek 朕會功夫 Derek 朕會功夫 - 6 months ago 10
CSS Question

Centering text around a point

Consider this:

<div id="point">
<div class="caption">Caption here</div>
</div>


Position is set on
#point
:

#point{
top: 50px;
left: 50px;
}


Now I want the text to be horizontally centered around the it. I tried making the
div
zero width

#point > .caption{
width: 0px;
text-align: center;
}


But apparently this doesn't work. So how do I center the text? It doesn't have to have two
div
s. It's just that I used two
div
s in attempt to make it work.

Answer

By using transform, we can horizontally (and/or vertically) center text around what would normally be its upper left corner (the point you are talking about).

The red dot (with the block class) is added to show the point we're centering around.

.caption {
  display: inline-block;
  position: absolute;
  top: 50px;
  left: 50px;
  transform: translate(-50%, -50%);
}

.block {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 5px;
  height: 5px;
  background-color: red;
  transform: translate(-50%, -50%);
}
<span class="caption">Caption here</span>
<div class="block"></div>

Comments