Skip to content Skip to sidebar Skip to footer

Can't Vertically Align:middle Absolutely Positioned Block Text

I'm having trouble vertically aligning some h2 text in the middle of a block. Basically I have a number of images with different heights all the same width (300px) with varying amo

Solution 1:

Solution without JS.

Add one extra element into HTML for background:

<div class="post-thumb">            
      <a href="http://eclectivism.com/text/">
           <span class="post-thumb-highlight"></span> <!-- HERE -->
           <h2 class="entry-title">Text text  text  text  text  text  text  text  text text text text text text text text text text text text text text text text</h2>
          <img src="http://eclectivism.com/wp-content/uploads/2013/09/space-doodle-01-580x7041.jpg" class="attachment-blog-large wp-post-image" />
       </a>
 </div>

with CSS:

.post-thumb-highlight {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    background: rgba(214,238,219,0.8);
    opacity: 0;
}

h2 {
    opacity: 0;
    text-decoration: none;
    display: inline-block;
    color: #fff;
    text-decoration: none;
    text-shadow: 0px 1px 5px rgb(63, 97, 56);
    text-align:center;
    width: 300px; /* same width as IMG */
    vertical-align: middle;
    margin-right: -300px; /* negative value of IMG width */
    position: relative;
    font-size: 24px;
}

img {
    width: 300px;
    vertical-align: middle;
}

a:hover h2, a:hover .post-thumb-highlight {opacity:1}

Check out demo - http://jsfiddle.net/3epgP/1/


Solution 2:

I put a div in center(vertical , horizontal) with this javascript lines:

 $('.dialogdiv').css('top', Math.max(0, (($(window).height() - $('.dialogdiv').outerHeight()) / 2) + $(window).scrollTop()) + 'px');
 $('.dialogdiv').css('left', Math.max(0, (($(window).width() - $('.dialogdiv').outerWidth()) / 2) + $(window).scrollLeft()) + 'px');

I hope this helps


Solution 3:

In CSS add:

left: 50%
top: 50%

minus the half the width and height of the text respectively for margins.

For example:

HTML:

<div>
<h3>Hello</h3>
</div>

CSS:

div {
height: 500px;
width: 500px;
}

h3 {
height: 50px;
width: 100px;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -25px;
}

Which will position in the center of the div.


Post a Comment for "Can't Vertically Align:middle Absolutely Positioned Block Text"