Align text in the vertical center of a circle

Asked

Viewed 2,689 times

3

How do I get the text inside the circle to be aligned in the vertical center as well?

CSS

.circle{
   position: absolute;
    background: red;
    border-radius: 52px;
    width: 37px;
    right: 308px;
    height: 37px;
    top: 90px;
    text-align: center;
    font-size: 10px;
    color: #FFF;
}

HTML

<div class='circle'>3</div>

View in jsfiddle

2 answers

3


If your text only has a single line, you can make the line-height is equal to the size of the div:

.circle{
    ...
    height: 37px;
    line-height: 37px;
    ...
}

Example. Otherwise, that answer in Soen shows more options. I personally only used in practice the line-height - integer for a line of text, half for two lines, etc., always being predictable the number of lines. So I don’t know how to evaluate solutions for an arbitrary number of lines.

2

An alternative is to work with flexbox. And for one simple reason: You don’t have to worry about the question of vertical and horizontal positioning, the property does all the work based on the rules defined.

An example:

.size-x {
    height: 100px;
    width:100px;
}

.circle {
    background: #333;
    color: #fff;
    border-radius: 50%;
    font-size: 2em;
    
    display: -webkit-flex;
     display: -ms-flexbox;
            display: flex;

    -webkit-align-items: center;
      -webkit-box-align: center;
	 -ms-flex-align: center;
	    align-items: center;
    
  justify-content: center;
}
<div class='size-x circle'>1</div>

At first it may seem a lot of code for something so simple, it turns out it is still an "experimental" property, so you need to use some prefixes.

But to show the question of "don’t worry about the alignment (...) flexbox take care of it" here are some examples increasing only the width and height of the same class used in the above example:

.circle {
    background: #333;
    color: #fff;
    border-radius: 50%;
    font-size: 2em;
    
    display: -webkit-flex;
     display: -ms-flexbox;
            display: flex;

    -webkit-align-items: center;
      -webkit-box-align: center;
	     -ms-flex-align: center;
	        align-items: center;
    
  justify-content: center;
}

.size-u {
    background: #1abc9c;
    height: 50px;
    width: 50px;
}

.size-v {
    background: #3498db;
    height: 100px;
    width: 100px;
}

.size-w {
    background: #9b59b6;
    height: 150px;
    width: 150px;
}

.size-x {
    background: #e74c3c;
    height: 200px;
    width: 200px;
}

.size-y {
    background: #f1c40f;
    height: 300px;
    width: 300px;
}

.size-z {
    background: #34495e;
    height: 500px;
    width: 500px;
}
<div class='size-u circle'>1</div>
<div class='size-v circle'>2</div>
<div class='size-w circle'>3</div>
<div class='size-x circle'>4</div>
<div class='size-y circle'>5</div>
<div class='size-z circle'>6</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.