Search code examples
htmlcsstwitter-bootstrapcenterabsolute

How to center absolute div (text) above relative div (image) responsively?


I'm building a template with Twitter Bootstrap and trying to get a text centered horizontally and vertically above a image, for example:

enter image description here

I'm trying with this:

<div class="container"> <!--Bootstrap-->
  <div class="row"> <!--Bootstrap-->
    <div class="col-md-4"> <!--Bootstrap-->

        <div class="box">
           <div class="thumb"><img src="..."></div>
           <div class="title">Post title</div>
        </div>

    </div> <!--Bootstrap-->
  </div> <!--Bootstrap-->
</div> <!--Bootstrap-->

.box {height:350px; width:100%; border:4px solid #fff;}
.thumb {position:relative; width:100%; height:100%; overflow: hidden;}
.thumb img{width:100%; height:100%; overflow: hidden;}
.title {position:absolute;}

With this, if I use some value to top to the div title it appears above the img, but I can't get to center it neither horizontally or vertically.

It doesn't work either with all I searched until now: left:50%, left:0 and right:0; margin:auto, etc...

Also I'm not looking for to use the img as a css background.

How can I get this right?


Solution

  • Your current code doesn't work because you are not applying top:0 and width:100% or left and right values. You also need to add position:relative to box so that the absolutely positioned title will place correctly. My suggestion to center the variably tall title is to use display:table-cell. The only problem with this (other than compatibility) is that it also requires another element added (some wrapping element around the text of .title). You can see this solution demonstrated here: http://jsfiddle.net/dx44c/3/

    Compatibility for table-cell: http://caniuse.com/#search=table

    required markup:

        <div class="box">
            <div class="thumb"><img src="//lorempixel.com/712/342"></div>
            <div class="title"><div>Post title</div></div>
        </div>
    

    the CSS needed:

    .box {position: relative; height:350px; width:100%; border:4px solid #fff;}
    .thumb {position:relative; width:100%; height:100%; overflow: hidden;}
    .thumb img{width:100%; height:100%; overflow: hidden;}
    .title {
        position:absolute;
        background: rgba(0,0,0,0.5);
        color: white;
        top: 0;
        width: 100%;
        height: 100%;
        text-align: center;
        display: table;
    }
    .title div {
        display: table-cell;
        vertical-align: middle;
        padding: 0 20%;
    }
    

    edit: better example added with more text and some padding on the table-cell