1

I have a DIV where I want the text to center vertically within that div. I can't use fixed pixel heights, only percentages.

<div style="position:relative; width: 100%; height: 100%;">

   <img src="images/thumb-member-placeholder.gif" alt=""  class="myImage"  /> 

    <div class="myText" style="display: inline-block; position: absolute; z-index:500; text-align:center;">Image Text</div>

</div>

I have 100 of these divs, where "myText" can be 1 line or 3 lines.

So I am using jquery to detect the height and set the TOP value accordingly:

        $(window).load(function() {


          var imageHeight = $('.myImage').height();


          $('.myText').each(function() {

            var textHeight =  $('.myText').height();


            var vertAdj = ((imageHeight - textHeight) / 2);
            $(this).css('top', vertAdj);

          });

        });

But it is not working. It outputs the same TOP value all the time, and does not detect the height of "myText" when the text goes to 2 or 3 lines.

Any suggestions?

4
  • 1
    var textHeight = $('.myText').height(); get the value of the first element in the stack, hence why it is all the same. Commented Feb 18, 2014 at 21:57
  • 4
    My suggestion avoid Jquery you can center vertically just with CSS . Commented Feb 18, 2014 at 21:57
  • Thanks Karl! How would I then modify my javascript so it would loop through the divs, and set the TOP value individually to each div? Commented Feb 18, 2014 at 22:02
  • var textHeight= $(this).height();. Commented Feb 18, 2014 at 22:17

1 Answer 1

2

Try this:

$('.myText').each(function(index,element) {

            var textHeight =  $(element).height();


            var vertAdj = ((imageHeight - textHeight) / 2);
            $(element).css('top', vertAdj);

          });

see the .each documentation for more http://api.jquery.com/each/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.