Css centering text in background image

I have a number inside a background image. I cannot place the number in the center of the circle. So far I have the number, but it is at the very top of the circle. How do I move it 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

+3


source to share


5 answers


All you have to do is set line-height

for your element p

such as line-height: 204px;

that which is equivalent to the element's height.

Demo



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

      

Also, I have no idea why you are using properties top

and left

here with a property z-index

, I think you can clean up the mess pretty much.

+2


source


Now check your script. 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;
}

      

+1


source


use line-height:

204px

This option is suitable when the text consists of one 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>
      

Run codeHide result


+1


source


One good solution is

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

      

Check Fiddle

+1


source


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

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

      

+1


source







All Articles