简体   繁体   中英

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). Thanks!

You could use flexbox. See the example:

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

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

I'd get rid of float and use table-cell s instead. Then, use vertical-align:middle for the text.

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>

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