Align text in the vertical center of a circle

3

How do I make the text from within the circle stay aligned in the vertical center too?

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

    
asked by anonymous 02.04.2015 / 22:00

2 answers

3

If your text has only one line, you can make line-height equal the size of div :

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

Example . Otherwise, this answer in SOen shows you 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 do not know how to evaluate the solutions for an arbitrary number of lines.

    
02.04.2015 / 22:07
2

An alternative is to work with flexbox . And for one simple reason: You do not have to worry about the vertical and horizontal placement issue, the property does all the work based on the defined rules.

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 like a lot of code for something so simple, it happens to be still an "experimental" property, so you have to use some prefixes.

But to show the issue of "do not worry about alignment ... flexbox" takes care of this "here are some examples only increasing 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>
    
02.04.2015 / 23:03