0

I have the following code

http://codepen.io/anon/pen/EZeVXG

HTML

<a href="#" class="col-inner">
 <img src="http://placehold.it/450x450" />
 <div class="content">
   <h3>Hello World</h3>
   <p>Lorem Ipsum Dolor Sit Amet</p>
 </div>
</a>

CSS

img{
 max-width: 100%;
 height: auto;
}
.col-inner{
 position: relative;
 display: inline-block;
}
.content{
 position: absolute;
 width: 90%;
 height: 90%;
 top: 5%;
 left: 5%;
 background-color: rgba(0,0,0,.7);
 color: #FFF;
 text-align: center;
}

I've tried a bunch of techniques found on Stack Overflow but everything seems to work only if you know the width and height. Both of those properties will change as you flex the browser. Is there any way to keep the text centered vertically the whole way?

soundslikeodd
  • 1,078
  • 3
  • 19
  • 32
Taylor Foster
  • 1,103
  • 1
  • 11
  • 24
  • Possible duplicate of [How to center an element horizontally and vertically?](http://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically) – chazsolo Feb 07 '17 at 19:28

2 Answers2

2

I found this trick on stackoverflow as well, I will add a link as soon as i find it again:

height: auto; // (this is the default)
position: absolute;
top: 50%;
transform: translateY(-50%);

That works because translateY takes the height of the element, and top uses the height of the surrounding element.

http://codepen.io/anon/pen/zNJvgg

Samuel Kirschner
  • 1,135
  • 1
  • 12
  • 18
0

You should try and use flexbox and if possible make some changes in your html.

In my opinion, to make this work I would use:

HTML

<a href="#" class="col-inner">
  <div class="content">
    <h3>Hello World</h3>
    <p>Lorem Ipsum Dolor Sit Amet</p>
  </div>
</a>

CSS

    .col-inner{
  max-width: 100%;
  min-height: 150px;
  position: relative;
  background-image: url('http://placehold.it/450x450');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
  display: flex;
  justify-content:center;
  align-items:center;
}
.content{
  color: #ff0000;
}

I just added the the image as background-image for the tag that acts as a container, and used display: flex; justify-content:center; align-items:center to horizontally & vertically center the text and all the elements inside the container.

You can tweak the height of .col-inner and see that no matter what height the class has, it will always be centered.

I've set a codepen to play with it: code

Keep in mind that if you want to use flexbox you should prefix your code. Use this website caniuse to see what prefixes you should add to flexbox and related properties.

Marian Ioan
  • 315
  • 1
  • 2
  • 14