4

I have tried a couple of techniques, but so far nothing works to center text in an absolutely centered sphere. The size of the sphere is known, but not the length of the text. Here is an example that is lacking vertical alignment:

http://jsfiddle.net/eevw3oes/

css:

div
{
    position: absolute;
    border-radius: 50%;
    top: 50px;
    width: 100px;
    height: 100px;
    background: yellow;
    overflow: hidden;
    vertical-align: middle;
    text-align: center;
}
Jakob Jingleheimer
  • 30,952
  • 27
  • 76
  • 126
no_gravity
  • 579
  • 1
  • 3
  • 14

3 Answers3

3

Flexbox to the rescue: http://jsfiddle.net/eevw3oes/2/

div {
    align-items: center;
    display: flex;
    …
}

This can also be accomplished by adding more DOM and using traditional css. I see you're trying to use vertical-align: middle, but that doesn't work on block elements (only with inline-block and table-cell).

Jakob Jingleheimer
  • 30,952
  • 27
  • 76
  • 126
2

Flexbox would work, and so will transforms:

<div class=circle style="left: 50px;">
    <div class=text>
    I'd like to be centered.
    </div>
</div>

<div class=circle style="left: 200px;">
    <div class=text>
    I would like also like to be centerd. Even though I have long text. I would like to be centerd horizontally and vertically. Is that possible. Oh I wish it would work.
  </div>
</div>

I've added inner <div> elements for the text. The CSS:

.circle {
    position: absolute;
    border-radius: 50%;
    top: 50px;
    width: 100px;
    height: 100px;
    background: yellow;
    overflow: hidden;
    padding: 20px;
}

div.text {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    height: auto;
}

CodePen.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Pretty awesome! If I could vote 2 answers as the solution, I would vote this one too. – no_gravity Oct 25 '14 at 16:56
  • This is good for a lot of situations where flexbox is not appropriate; however, this is more expensive to render. Also, if you try to do css animations/transitions, `transform` accepts multiple functions (scale, translate, etc), and their order matters, so manipulating them is difficult. – Jakob Jingleheimer Dec 08 '15 at 02:23
  • @jacob It's expensive I guess, but how many elements are you going to be vertically centering? If it's 300 or 5000 or whatever, then yes the performance is worth thinking about. I suspect that for a lot of designs it's one or two elements. – Pointy Dec 08 '15 at 06:10
  • 1
    I suspect that as well. Just pointing out the perf implications. Also, combining hardware-accelerated props with absolute/fixed positioning can cause a baffling rendering bug in webkit. – Jakob Jingleheimer Dec 08 '15 at 06:18
1

I think you could add line-height with the same value as width

line-height: 100px;

See this Fiddle

Someone had already a similar problem on Stackoverflow.

Community
  • 1
  • 1
pbaldauf
  • 1,671
  • 2
  • 23
  • 32