Corzuu Corzuu - 7 days ago 8
HTML Question

Center text horizontally and vertically in a circle

I'm having an issue where the text isn't appearing in the center of the circle, how can I fix that please? Here is the JSFiddle.



#indexClient {
float: left;
margin-top: 10px;
margin-left: 20px;
width: 150px;
height: 150px;
border-radius: 50%;
font-size: 30px;
color: yellow;
line-height: 20px;
text-align: center;
background: #99CCCC
}

<div id="indexClient">
<p>Client Side</p>
</div>




Answer

Approach 1: line-height equal height tricks (works for single line of text).

.circle {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    font-size: 30px;
    background: #9cc;
    line-height: 150px;
    text-align: center;
}
<div class="circle">Hello</div>

Approach 2: line-height + inline-block (works for both single and multiple lines of text).

.circle {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    font-size: 30px;
    background: #9cc;
    line-height: 150px;
    text-align: center;
}
.circle span {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
    padding: 0 25px;
}
<div class="circle">
    <span>Test Long Item</span>
</div>

Approach 3: using CSS table + table-cell (works for both single and multiple lines of text).

.circle {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    font-size: 30px;
    background: #9cc;
    text-align: center;
    display: table;
}
.circle span {
    display: table-cell;
    vertical-align: middle;
    padding: 0 25px;
}
<div class="circle">
    <span>Test Long Item</span>
</div>

Approach 4: using CSS3 transform (works for both single and multiple lines of text).

.circle {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    font-size: 30px;
    background: #9cc;
    text-align: center;
    position: relative;
}
.circle span {
    position: absolute;
    left: 50%;
    top: 50%;
    -ms-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
<div class="circle">
    <span>Test Long Item</span>
</div>

Comments