Center Text Vertical In Element That Changes Height And Width
Solution 1:
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
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"