Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering text around a point

Tags:

html

css

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 divs. It's just that I used two divs in attempt to make it work.

like image 911
Derek 朕會功夫 Avatar asked Oct 24 '25 14:10

Derek 朕會功夫


1 Answers

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>

Version that uses two elements and relative positioning instead of transform:

.caption {
  display: inline-block;
  position: absolute;
  top: 50px;
  left: 50px;
}

.inner {
  position: relative;
  left: -50%;
  top: -0.5em;
}

.block {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 5px;
  height: 5px;
  background-color: red;
  transform: translate(-50%, -50%);
}
<span class="caption"><span class="inner">Caption here</span></span>
<div class="block"></div>
like image 73
Maximillian Laumeister Avatar answered Oct 27 '25 03:10

Maximillian Laumeister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!