John Smith
John Smith

Reputation: 6197

Aligning a text vertically center, middle of image - with automatic line height

here is the fiddle:

<div style="background-color: yellow;">
    <div style="background-color: red; float: left;">1</div>
    <div style="background-color: green; float: left;"><img src="http://static.idokep.hu/images/nagyelore/ujikon2/030.png" width="108" height="50" /></div>
</div>

http://jsfiddle.net/LgyjZ/

I know the goal can be achieved by adding "line-height: 50" to the first div (not done in the fiddle). But lets suppose I can variate the height many times and I dont want to set the lineheight too. Can it be somehow 100%?

Upvotes: 0

Views: 158

Answers (2)

Morpheus
Morpheus

Reputation: 9065

You need to add vertical-align: middle. Changed structure a little bit:

.text {
    background-color: red;
    display: inline;
    vertical-align: middle;
}

img {
    vertical-align: middle;
}
<div style="background-color: yellow;">
    <div class="text">1</div>
    <img src="http://static.idokep.hu/images/nagyelore/ujikon2/030.png" width="108" height="50" />
</div>

Example

Upvotes: 3

GL.awog
GL.awog

Reputation: 1322

  1. If you want to preserve the current html structure, change 'display' property for all divs - the wrapper and the two containers, and discard their 'float' property.

http://jsfiddle.net/P4LxQ/1/

  #wrapper {
    display:table-row;   
}

 #text {
    display:table-cell;
    float:none !important;
    height:100px;
   vertical-align:middle;    
 }

 #pic {
    display:table-cell;
    float:none !important;    
    vertical-align:middle;
 }
  1. if it's necessary to preserve the float behaviour of the divs, this only can be done with javascript, that will adjust height and line-height of the div with text.

http://jsfiddle.net/U9m96/

 $(document).ready(function() {
    var picHeight =  $("#pic").outerHeight();
    $("#text").css({"height": picHeight, "line-height":picHeight+"px"}); 
 });

Upvotes: 1

Related Questions