Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Robert James
Robert James
20,491 Points

vertically center an image within a div that has no fixed height

I am using foundation as a building block for a project. I have a 2 divs within another div which are next to each other, one with text the other is an image. There is no fixed height to the divs as they are responsive so the height is pretty much dependent on the length of the text. I want to center the image vertically to the div so that it lines up to the center of the opposite div (the one with the text in)

Thanks

1 Answer

rydavim
rydavim
18,813 Points

I don't know of an elegant way to do this, but I'll detail an inelegant way below.

<div class="container">
  <div class="text">
    <!-- YOUR TEXT ELEMENTS HERE -->
  </div>
  <div class="img">
    <!-- YOUR IMG HERE -->
  </div>
</div>
.container {
  position: relative;
  width: 100%;
}

.text {
  width: 55%; 
}

.img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  right: 0;

  text-align:center;
  font: 0/0 a;
}

.img:before {
  content: ' ';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

.img img {
  vertical-align: middle;
  display: inline-block;
  max-width: 100%;
  max-height: 100%;
}

For help specifically with your Foundation based layout, please post your code structure here. I'm not very familiar with that framework, but I'll do my best if the above example doesn't help you.