marse
marse

Reputation: 873

css centering text within a background image

I have a number inside a background image. I can't put the number in the center of the circle. So far, I have center the number but it is in the topmost part of the circle. How do I move it down to the center?

HTML code:

<div class="number">
  <p>
  576
  </p>
</div>

CSS code:

.number{
    float:left;
    background-position: center;
    text-align: center;
    font-size:200%; 
    }

.number p{  
    position:relative;
    top: 38%;
    left:57%;
    z-index:999;    
    background-image: url("http://davidwalsh.name/demo/css-circles.png");
    width: 207px;
    height: 204px;
    }

Here is the jsfiddle

Upvotes: 3

Views: 300

Answers (5)

stanze
stanze

Reputation: 2480

Add the below CSS properties inside this class .number p{}

display: table-cell;
vertical-align: middle;

Upvotes: 1

ketan
ketan

Reputation: 19341

One of the good solution is

display: table-cell;
vertical-align: middle;

Check Fiddle

Upvotes: 1

Nilesh Mahajan
Nilesh Mahajan

Reputation: 3516

check your fiddel now.https://jsfiddle.net/ydz8cn7b/1/

I have updated it as per your requirement:

HTML

<div class="number">
    <p>576</p>
</div>

CSS

.number {
    float:left;
    background-position: center;
    text-align: center;
    font-size:200%;
    display:table;
}
.number p {
    display:table-cell;
    background-image: url("http://davidwalsh.name/demo/css-circles.png");
    width: 207px;
    height: 204px;
    vertical-align:middle;
}

Upvotes: 1

Dmitriy
Dmitriy

Reputation: 4503

use line-height: 204px

This option is suitable when the text consists of a single line

.number{
	float:left;
	background-position: center;
	text-align: center;
	font-size:200%;	
	}
	
.number p{	
	position:relative;
	top: 38%;
	left:57%;
	z-index:999;	
	background-image: url("http://davidwalsh.name/demo/css-circles.png");
	width: 207px;
	height: 204px;
    line-height: 204px;
	}
<div class="number">
	<p>
   	576
   	</p>
   	</div>

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157334

All you need to do is to set a line-height for your p element like line-height: 204px; which is equivalent to the element height.

Demo

.number p {
    /* Other properties here */
    line-height: 204px; /* add this */
}

Also, I have no idea why you are using top and left properties here with z-index property, I think you can clean up the mess by a great extent.

Upvotes: 2

Related Questions