Reputation: 1215
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?
Upvotes: 0
Views: 57
Reputation: 1185
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
Upvotes: 2
Reputation: 317
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.
Upvotes: 0