3

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!

  • I would try something like this [FIDDLE](https://jsfiddle.net/Lf2fk8cc/2/) – Abhi Oct 01 '16 at 14:47
  • 1
    Possible duplicate of [Vertically align text next to an image?](http://stackoverflow.com/questions/489340/vertically-align-text-next-to-an-image) – Rob Oct 01 '16 at 17:53
  • 1
    Instead of "Centering Vertical Text" I think you mean "Vertically Centering Text". Otherwise, it sounds like it's the *text* that's vertical, rather than the axis upon which it's being centered. – Phantom Watson Feb 17 '17 at 22:29

3 Answers3

6

You could use flexbox. See the example:

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

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

marcelo2605
  • 2,734
  • 4
  • 29
  • 55
2

I'd get rid of float and use table-cells 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>
blurfus
  • 13,485
  • 8
  • 55
  • 61
0
h1 {
  display: inline;
   vertical-align:top;
}

<div class="middle">
  <img src="http://placekitten.com/200/150" >
   <h1>A TEXT</h1>
</div>
Razia sultana
  • 2,168
  • 3
  • 15
  • 20