简体   繁体   English

HTML + CSS用于居中图像旁边的垂直文本

[英]HTML + CSS for Centering Vertical Text next to an Image

Hi Everybody and tks in advance for your help... I'm looking for the best practice to resolve a simple question: 大家好,请提前帮忙...我正在寻找解决一个简单问题的最佳做法:

 .left { float: left; width: 79%; margin-right: 1%; } .left img { float: right; } .right { float: right; width: 20%; } 
 <div class="main"> <div class="left"> <img src="http://placehold.it/200x200" /> </div> <div class="right">A TEXT</div> </div> 

How should I center the text vertically at the middle of the image (obviusly not using px in margin-top or bottom, because the width/height of the image will be dinamic). 我应该如何将文本垂直居中放置在图像的中间(显然不是在边缘顶部或底部使用px,因为图像的宽度/高度将是动态的)。 Thanks! 谢谢!

You could use flexbox. 你可以使用flexbox。 See the example: 看例子:

.main{
   display: flex;
   align-items: center;
}

https://jsfiddle.net/zb2ozq1k/1/ https://jsfiddle.net/zb2ozq1k/1/

I'd get rid of float and use table-cell s instead. 我将摆脱float并使用table-cell Then, use vertical-align:middle for the text. 然后,使用vertical-align:middle作为文本。

Like this: 像这样:

 .main{ display: inline-table; border: 1px solid blue; } .left { width: 79%; margin-right: 1%; display: table-cell; border: 1px solid green; } .right { width: 20%; border: 1px solid red; display: table-cell; vertical-align: middle; } 
 <div class="main"> <div class="left"> <img src="http://placehold.it/200x200" /> </div> <div class="right">A TEXT</div> </div> 

h1 {
  display: inline;
   vertical-align:top;
}

<div class="middle">
  <img src="http://placekitten.com/200/150" >
   <h1>A TEXT</h1>
</div>

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

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