Haitch Haitch - 2 months ago 7
CSS Question

Can't make element 100% height when using 'display:table' and 'masonry'

I am using masonry to display images.
I wish to have text appear in the middle of each image and to do this I have displayed a parent as table and the child as table-cell.
I can't get the parent wrapper to 100% height.

<div class="grid">
<div class="grid-sizer"></div>
<div class="grid-item">
<div class="wrapper">
<div class="title">
<h1>Title Here</h1>
</div>
</div>
<img src="any-image.jpg"/>
</div>




.grid-sizer, .grid-item {
width: 33.333%;
}
.grid-item {
float: left;
overflow:hidden;
position:relative;
}
.wrapper {
display:table;
position:absolute;
text-align:center;
width:100%;
height:100%;
top:0;
bottom:0;
left:0;
right:0;
}
.title {
display: table-cell;
vertical-align: middle;
width:100%;
height:100%;
}
.grid-item img {
display: block;
}


I also understand that if I define the height of
.grid-item
the text will centre but this changes with the viewport size and therefore I cannot define a single size.

Here is a fiddle if it helps: https://jsfiddle.net/j32921b9/

Thanks for any help.

Answer

I may suggest you another approach, without using tables. Add absolute position to your text wrapper add transform it like so:

.title {
   display: inline-block;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   color:#fff;
 }

Here updated fiddle.