Vertically and horizontally centering text in circle in CSS (like iphone notification badge)
Horizontal centering is easy: text-align: center;
. Vertical centering of text inside an element can be done by setting line-height
equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.
Better is to set line-height
equal to font-size
(or slightly smaller) and use padding. You'll have to adjust your height to accomodate.
Here's a CSS-only, single <div>
solution that looks pretty iPhone-like. They expand with content.
Demo: http://jsfiddle.net/ThinkingStiff/mLW47/
Output:
CSS:
.badge {
background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
background-color: red;
border: 2px solid white;
border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
box-shadow: 1px 1px 1px black;
color: white;
font: bold 15px/13px Helvetica, Verdana, Tahoma;
height: 16px;
min-width: 14px;
padding: 4px 3px 0 3px;
text-align: center;
}
HTML:
<div class="badge">1</div>
<div class="badge">2</div>
<div class="badge">3</div>
<div class="badge">44</div>
<div class="badge">55</div>
<div class="badge">666</div>
<div class="badge">777</div>
<div class="badge">8888</div>
<div class="badge">9999</div>
Modern Solution
The result is that the circle never gets distorted and the text stays exactly in the middle of the circle - vertically and horizontally.
.circle {
background: gold;
width: 40px;
height: 40px;
border-radius: 50%;
display: flex; /* or inline-flex */
align-items: center;
justify-content: center;
}
<div class="circle">text</div>
Simple and easy to use. Enjoy!
If you have content with height unknown but you know the height the of container. The following solution works extremely well.
HTML
<div class="center-test">
<span></span><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Nesciunt obcaecati maiores nulla praesentium amet explicabo ex iste asperiores
nisi porro sequi eaque rerum necessitatibus molestias architecto eum velit
recusandae ratione.</p>
</div>
CSS
.center-test {
width: 300px;
height: 300px;
text-align:
center;
background-color: #333;
}
.center-test span {
height: 300px;
display: inline-block;
zoom: 1;
*display: inline;
vertical-align: middle;
}
.center-test p {
display: inline-block;
zoom: 1;
*display: inline;
vertical-align: middle;
color: #fff;
}
EXAMPLE http://jsfiddle.net/thenewconfection/eYtVN/
One gotcha for newby's to display: inline-block; [span] and [p] have no html white space so that the span then doesn't take up any space. Also I've added in the CSS hack for display inline-block for IE. Hope this helps someone!