redconservatory
redconservatory

Reputation: 21924

How to center text with a background image

I really would like to do something like this...it's for when I have text with icons on the left:

enter image description here

I tried (unsuccessfully) to do something along the lines of:

    <a href="#" class="icon">Text centered vertically in relation 
to the background image</a>

CSS

a.icon {
background: url(image.png) 0 50%;
margin-top: -5%;
min-height: the-height-of-my-image-plus-the-negative-margin;
}

Upvotes: 4

Views: 2393

Answers (3)

Gaston Morixe
Gaston Morixe

Reputation: 847

I can't think of a perfect solution, but the following code may work. However, it breaks anchors-links spec, and it's a very bad practice.

CSS

<style type="text/css">
.fixinline {
 display: inline-block;
}
.icon { 
 background: red url(http://goo.gl/12gdn) no-repeat left center;
 height: 135px; /* >= image height */
 display: table;
 padding: 0 0 0 135px; /* >= image height */
}
.icon span {
 display: table-cell;
 background-color: yellow;
 vertical-align: middle;
}
</style>

HTML

<span class="fixinline"><a class="icon"><span>hello<br>there</span></a></span>

jsFiddle Demo

Upvotes: 0

gingerbreadboy
gingerbreadboy

Reputation: 7769

a.icon {
background: url(image.png) 0 50%;
padding: ?px ?px
}

Adjust the padding ?px

Upvotes: 1

sandeep
sandeep

Reputation: 92793

Give line-height same as height of your a tag. Like this:

a.icon {
background: url(image.png) 0 50%;
margin-top: -5%;
height:40px;
line-height:40px;
text-align:center;
}

Upvotes: 3

Related Questions