如何使背景图像与文本垂直居中对齐?

20
我在垂直对齐背景图像和文本方面遇到了问题,而不需要为heightline-height分配固定(因此不是自动且可重复使用的)值。 我想知道是否有一种方法可以垂直居中对齐例如a元素的背景图像和其文本,而不需要将常量值分配给line-heightheight
这里提供了一个实时演示:http://cssdesk.com/8Jsx2
以下是HTML代码:
<a class="">background-position: center</a>
<a class="contain">background-size: contain</a>
<a class="line-height">Constant line-height</a>

以下是CSS代码:

a {
  display: block;
  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: 5px center;

  border: 1px solid black;
}

/* I don't want to use constant line-height */
.line-height {
    line-height: 24px;
}

/* I don't want to use this, because I want my bg image's size to stay intact */
.contain {
    background-size: contain;   
}

这可能是如何在div中垂直居中图像的重复问题。 - JabberwockyDecompiler
3个回答

41

2
我认为仅使用CSS不可能实现这一点,因为背景图像不会影响其包含元素的高度。您需要检测背景图像的大小,这需要使用Javascript。在Javascript中检测元素的宽度和高度涉及从背景图像创建一个img
下面是一种解决方案,它使用Javascript和display: table来实现所需的结果:
工作示例: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);

}); 

我根据以下来源如何在jQuery中获取背景图像大小?给出了我的答案。

1

通过使用 background css 属性来将背景图片居中,您可以始终保持其居中。问题在于文本对控件的中间对齐。

您是否考虑过使用 em 单位来指定行高?您需要指定某种高度以允许垂直居中发生。

或者,如果您不想使用 em,您可以尝试使用 display:table-cell css 属性。

请查看 - http://cssdesk.com/3ZXrH - 上述两个示例。我已添加了 height:10em; 以更好地演示正在发生的事情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接