cup_of cup_of - 27 days ago 6
CSS Question

Is it possible to vertically center a relatively positioned element?

I am trying to vertically center an image. I know how to do it with absolute position, but the problem with this is that other elements around it collapse into it.

This is how I vertically center using absolute position:

.element {
position: absolute;
top: 50%;
transform: translateY(-50%);
}


I'd like to use relative position, but when I change absolute to relative, it does not work. Anyone have any suggestions to vertically center using relative position? I could do padding/margin top until its centered but I would like the css to generate it centered in case the image changes height when responsive.

This is the HTML and CSS, its pretty simple:

<div class="header-main-left">
<img src="/images/header_logo.png" >
</div>

.header-main-left {
float: left;
height: 95px;
position: relative;
}

.header-main-left img {
position: absolute; //I want this to be position relative
top: 50%;
transform: translateY(-50%);
}

Answer

position:relative does not take an element out of the flow, it just allows you to change its render location relative to where it would've been rendered had it not been positioned.

position:absolute takes an element out of the document flow. This causes the elements origin to be the upper left of the nearest ancestor element that is not position:static.

If you need to set your particular element to position:relative, but need its initial position to be centered in its parent, add a wrapper element and move the centering to that wrapper.

.header-main-left {
    float: left;
    height: 95px;
    position: relative;
}

.header-main-left .logo-wrapper {
    position:absolute;
    top:50%;
    height:100%; /* let the relative top and transform on the img work */
}

.header-main-left img {
    position: relative; /* I want this to be position relative */
    top:50%;
    transform: translateY(-50%);
}
<div class="header-main-left">
  <div class="logo-wrapper">
    <img src="/images/header_logo.png" >
  </div>
</div>