How to vertically center align background image with text?

断了今生、忘了曾经 提交于 2019-12-03 04:58:43

Try using two words to align your background with css.

background-position: left center;

Reference: http://www.w3schools.com/cssref/pr_background-position.asp

UPDATE:

Adding another link from comments. Grant Winney shared another site that has a much better interface for how this works.

https://developer.mozilla.org/en-US/docs/Web/CSS/background-position

littledynamo

I don't think this is possible with CSS alone because background images don't affect the height of their containing element. You would need to detect the size of the background image and that would require javascript. Detecting the width and height of an element in Javascript involves creating an img from the background image.

Here is a solution that uses Javascript and display: table to achieve the desired result:

Working example: http://jsbin.com/olozu/9/edit

CSS:

div {
    display: table; 
}

a {
    display: table-cell;
    vertical-align: middle;
    margin: 10px;
    width: 200px;
    padding-left: 34px;
    font-size: 14px;  

    background: url('http://cdn1.iconfinder.com/data/icons/freeapplication/png/24x24/Thumbs%20up.png');  
    background-repeat: no-repeat;
    background-position: 0 0;
    border: 1px solid black;
}

HTML:

<div><
    <a id="example-a">background-position: center</a>
</div>

JS:

$(function() {

    var imageSrc = $('#example-a')
                 .css('background-image')
                   .replace('url(', '')
                      .replace(')', '')
                      .replace("'", '')
                      .replace('"', '');   

    var image = '<img style="display: none;" src="' + imageSrc + ' />';

    $('div').append(image);

    var width = $('img').width(),
        height = $('img').height(); 

    // Set the height of the containing div to the height of the background image
    $('#example-a').height(height);

}); 

I based my answer on the following source How do I get background image size in jQuery?

By using the background css to center the background image you will have it always centred. The issue is the alignment of the text to the middle of the control.

Have you considered using the em units to specify line height? You will need to specify some kind of height to allow the vertical centre to take place.

Alternatively, if you do not want to use em, you can try display:table-cell css.

Check - http://cssdesk.com/3ZXrH - for the above two examples. I have added height:10em; to better demonstrate what is going on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!