简体   繁体   English

将文字垂直居中对齐至图像中间-自动行高

[英]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/ 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). 我知道可以通过在第一个div上添加“ line-height:50”来实现目标(在小提琴中没有完成)。 But lets suppose I can variate the height many times and I dont want to set the lineheight too. 但是假设我可以多次改变高度,而我也不想设置线高。 Can it be somehow 100%? 能以某种方式100%吗?

You need to add vertical-align: middle . 您需要添加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. 如果要保留当前的html结构,请为所有div(包装器和两个容器)更改“ display”属性,并丢弃其“ float”属性。

http://jsfiddle.net/P4LxQ/1/ 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. 如果有必要保留div的float行为,则只能使用javascript来完成,这将使用文本调整div的高度和行高。

http://jsfiddle.net/U9m96/ http://jsfiddle.net/U9m96/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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