Search code examples
htmlcsscss-positionvertical-alignment

Vertically centering, absolute position, multiple elements


I'm using the following approach to vertically center an element with unknown height in a div with unknown height.

http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

The elements that I'm centering are anchor tags, so this answer solves the position relative issue.

When to use position absolute vs position relative when vertically aligning with css

However since I have one element next to the other, they overlap when using position:absolute

Is there any way that I can solve this? (I cannot use flexbox)

HTML:

<div class"parent-container">
  <a href="">Some content</a>
  <a href=""><img src""></a>
</div>

CSS

.parent-container {
 -webkit-transform-style: preserve-3d;
 -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.parent-container a {
 position: absolute;
 top: 50%;
 transform: translateY(-50%);
}

Solution

  • Make the children inline-block and use vertical-align:middle. No need for positioning.

    a {
      vertical-align: middle;
      display: inline-block;
    }
    .parent-container {
      text-align: center;
      background:palegoldenrod
    }
    <div class="parent-container">
      <a href="">Some content</a>
      <a href="">
        <img src="http://www.fillmurray.com/140/100">
      </a>
    </div>

    If the containing parent is taller than the content you can use a pseudo-element.

    a {
      display: inline-block;
      vertical-align: middle;
    }
    .parent-container {
      text-align: center;
      height: 150px;
      background: pink;
    }
    .parent-container::before {
      content: '';
      height: 100%;
      display: inline-block;
      vertical-align: middle;
      margin-right: -0.25em;
      /* Adjusts for spacing */
    }
    <div class="parent-container">
      <a href="">Some content</a>
      <a href="">
        <img src="http://www.fillmurray.com/140/100">
      </a>
    </div>