Skip to content Skip to sidebar Skip to footer

Center Text Vertical In Element That Changes Height And Width

I have the following code http://codepen.io/anon/pen/EZeVXG HTML

Solution 1:

Solution 2:

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

<ahref="#"class="col-inner"><divclass="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.

Post a Comment for "Center Text Vertical In Element That Changes Height And Width"