0

enter image description here

As you can see from the above picture, how can I vertically align them to the middle of the grey box, where they have equal height of top and bottom.

Code:

<div style="height: 290px; width: 210px; background-color: grey;">
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
</div>

I tried with the above style, but it seems to only adjust the top of the picture. I can't get it to align to the middle. Any help would be much appreciated. Thanks

NewbieCoder
  • 666
  • 7
  • 31

5 Answers5

1

Since the images are inline elements by default, use the methods that apply to vertically center text with CSS will work for this case.

For example, use line-height will work like this:

<div style="height: 290px; width: 210px; background-color: grey; line-height:250px;">
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
</div>

Use flex box will also works fine. If you are willing to set the img to a block element, then you can use some other tricks like transform or negative margin.

For example:

<div style="height: 290px; width: 210px; background-color: grey; position: relative;">
    <img src="${ImagePopulator}${MainProductImage}"style="display: block; margin-top:-145px;top 50%; position:relative; height: 100%; padding: 20px 0;"/>
    <img src="${ImagePopulator}${MainProductImage}"style="display: block; margin-top:-145px;top 50%; position:relative; height:100%; padding: 20px 0;"/>
</div>
Jack Q
  • 301
  • 1
  • 2
  • 9
0

Add these css to the element you want to align in the center.

position: relative;
top: 50%;
transform: translateY(-50%);

Look at this fiddle

mattdevio
  • 2,271
  • 1
  • 13
  • 28
0

You can try this css -

display: flex; or, -webkit-flex
justify-content: center;
align-items: center;
flex-direction: column; or, row
s.k.paul
  • 6,663
  • 24
  • 88
  • 159
0

Use the following styling, added to your code:

<div style="height: 290px; width: 210px; background-color: grey; display:table-cell; vertical-align:middle; text-align:center">
    <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTKfww8iUXidrKRO9vnHq3rWTJdcXK8YCIhSPTMxrQ9yD1EdlnX" style="padding: 20px 0;"/>
</div>

Here is a working example with the above code.

Which produce the following:

enter image description here

Alon Adler
  • 3,789
  • 4
  • 29
  • 43
0

You can try like this

.block{
  display: table-cell;
  vertical-align: middle;
  height: 120px;
  background: rgba(0,0,0,.3);
}
img{
  height: 30px;
}
 <div class="block">
  <img src="https://raw.githubusercontent.com/ModernPGP/icons/master/keys/icon-fingerprint.png">
 </div>

When you use display: table-cell then you are able to use vertical-align CSS property

Sumon Sarker
  • 2,526
  • 1
  • 22
  • 33