DataDev DataDev - 2 months ago 7
HTML Question

Vertical align button beside image

I am trying to get my link to vertical align center in the middle and my logo to vertical align in the middle but off to the right as the image below shows. I can get the image to work perfectly. but i cannot get the link vertical aligned middle.

this will also be full width across.

view layout image



.footer-logo {
display: block;
position: absolute;
right: 50px;
margin-top: 30px;
}

.footer-main {
height: 200px;
background-image: url(../images/backgrounds/bg-image.jpg);
background-color: grey;
position: relative;
text-align: center;
vertical-align: middle;
}

<div class="footer-main">
<a class="button" href="#">My test link here</a>
<img src="http://placehold.it/100" alt="" class="footer-logo">
</div>




Answer

there is no top-margin in CSS only margin-top or top

OPTION A use display:flex on the container , #footer in this case, together with align-items: center; and justify-content: center;

where align-items aligns the items inside the flexbox vertically
and justify-content aligns them horizonally

DOCs:

OPTION B ( after comments ) seems like in firefox, applying align-items:center doesn't affect an element with position:absolute; so i've added transform:translateY(-50%) together with top:50% on the logo.

this works because , top:50% reffers to 50% of the footers height, and translateY(-50%) refers to 50% of the logo's height , so basically you move from top to bottom the logo with 50% of the footer height, then move it back up with 50% of it's own height and the result is that it is vertically centered.

OPTION C

using display:inline-block together with vertical-align:middle on the .footer-logo will also work.

OPTION D

one more option would be to use top:calc(50% - 50px) on the .footer-logo but this works only if the height of the logo stays constant. it's not recommended to use this method but it's a good use of the calc() CSS function

you choose ;)

.footer-logo {
display: block;
position: absolute;
right: 50px;   
transform: translateY(-50%);
top:50%;

}

.footer-main {
height: 200px;
background-color: grey; 
position: relative;



  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="footer-main">
<a class="button" href="#">My test link here</a>
<img src="http://placehold.it/50x100" alt="" class="footer-logo">
</div>