简体   繁体   中英

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%?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM