2012-11-17 13 views
14

一定の(したがって自動ではなく再利用可能な)値をheightまたはline-heightに割り当てずに、背景イメージをテキストと垂直に整列させるのに問題があります。私は実際には、例えば、a要素, with its text without assigning constant values to行の高さの垂直方向の中心にbgイメージの方法があるのだろうかと思っていた `高`?背景とテキストを垂直方向に合わせる方法は?

ライブデモは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; 
} 
+0

可能重複[divの内側の中央の画像を縦にする方法](http://stackoverflow.com/questions/2237636/how-to-vertically-center-image-inside- div) – JabberwockyDecompiler

答えて

1

centerにあなたはそれが常に集中しているだろう背景画像をbackground CSSを使用することにより。問題は、コントロールの中央にテキストを配置することです。

em単位を使用して行の高さを指定することを検討しましたか?垂直中心が起こるには、ある程度の高さを指定する必要があります。

また、emを使用しない場合は、display:table-cell cssを試すこともできます。

チェック - http://cssdesk.com/3ZXrH - 上記2つの例については、私はheight:10em;を追加して、何が起こっているかをよりよく実証しました。

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); 

}); 

私はCSSであなたの背景を揃えるために2つの単語を使用してみてください、次のソースHow do I get background image size in jQuery?

関連する問題