0

I'm trying to make a circle shaped div with some text directly in the middle. I can get it horizontally in the middle, easily but I am having loads of trouble getting it in the vertical center, I've tried doing vertical-align, padding, display etc but it'll always stay right at the top.

Here's the offending HTML:

<div class="widget">
    <p id='case'>{27 cases}</p>
</div>

And here's the CSS for that div:

.widget {
    background-color: #ff1122;
    color: yellow;
    width: 150px;
    height: 150px;
    border-radius: 100%;
    text-align: center;
    font-size: 24px;
    vertical-align: middle;
}

I'm trying to get the text precisely in the middle of the circle vertically. How can I do this?

HJGBAUM
  • 297
  • 5
  • 16

3 Answers3

0

You need to add the line-height property. Make the line-height equal to the height of the circle, in this case 150px.

line-height:150px;

.widget {
    background-color: #ff1122;
    color: yellow;
    width: 150px;
    height: 150px;
    border-radius: 100%;
    text-align: center;
    font-size: 24px;
    vertical-align: middle;
    line-height:150px;
}
<div class="widget">
    <p id='case'>{27 cases}</p>
</div>

If you are open to using flex-box you can also do this instead. This will work for multiple lines.

.widget {
    background-color: #ff1122;
    color: yellow;
    width: 150px;
    height: 150px;
    border-radius: 100%;
    text-align: center;
    font-size: 24px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
<div class="widget">
  <p id='case'>This is multiple line text.</p>
</div>
Wowsk
  • 3,637
  • 2
  • 18
  • 29
  • 1
    This will create issues if the text is multiple lines. I believe using `display: table-cell` would be a more use-case solution personally, but to each their own. – Tyler Roper Aug 08 '16 at 15:26
  • I updated my answer to include two ways, one for single line and the other for multiple lines. – Wowsk Aug 08 '16 at 15:31
0

Take a look at this:

.widget {
    background-color: #f12;
    color: yellow;
    width: 150px;
    height: 150px;
    border-radius: 100%;
    text-align: center;
    font-size: 24px;
}

.widget * {
  display:inline-block;
  vertical-align: middle;
}

.widget::before {
  content: "";
  display:inline-block;
  width: 0;
  height: 100%;
  vertical-align: middle;
}
<div class="widget">
    <p id='case'>{27 cases}</p>
</div>
hmak.me
  • 3,770
  • 1
  • 20
  • 33
0

Make the circle display: table; and the inside p have display: table-cell; and vertical-align: middle;.

.widget {
    background-color: #ff1122;
    color: yellow;
    width: 150px;
    height: 150px;
    border-radius: 100%;
    text-align: center;
    font-size: 24px;
    display: table;
}

.widget p {
    display: table-cell;
    vertical-align: middle;
}
<div class="widget">
    <p id='case'>{27 cases}</p>
</div>
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56