0

I'm having an issue with vertically centering content within a slider, I have managed to get it working on resize but my javascript doesn't work on page load for some reason.

I get the feeling this might be due to the fact the content is positioned absolute and maybe doesnt have a height value on load? But thats just a wild guess.

Here is the example: DEMO

<div id="slides">
    <ul class="slides-container">
        <li>
            <div class="slider_content">
                <h1>Some Text</h1>
                <p>Quisque ultrices, libero eget aliquet consequat, sapien leo sollicitudin ligula, fermentum luctus enim libero a neque. Nam dapibus, lectus nec condimentum volutpat, diam nisl cursus odio, vitae luctus libero augue at dolor. Nullam ut quam ut augue facilisis ultrices eget non risus.</p>
            </div>

            <img src="http://nicinabox.com/superslides/images/building.jpg" width="1024" height="682" alt=""/>

        </li>
    </ul>
</div>

// VERTICALLY ALIGNS THE SLIDER CONTENT ON LOAD (NOT WORKING)

$(window).load(function() {
    $('.slider_content').each(function(event) {
        $(this).css({"margin-top": - ( $(this).outerHeight()/2 ) });
    });
});

// VERTICALLY ALIGNS THE SLIDER CONTENT ON RESIZE (WORKING)

$(document).ready(function() {
    $(window).resize(function() {
        $('.slider_content').each(function(event) {
            $(this).css({"margin-top": - ( $(this).outerHeight()/2 ) });
        });
    });
});

Thanks for any help!

Lighty_46
  • 5,010
  • 1
  • 16
  • 17
  • Can't this all be done with CSS3 and a `transform:translate`. I do it all the time. – Paulie_D Jun 23 '14 at 14:50
  • @Paulie_D Probably, but the browser support isn't great, which is why I went down the javascript route .... also CSS wouldn't be able to do this for EACH content div could it? (for each slide of the slider, as the content on each slide will be different sizes) – Lighty_46 Jun 23 '14 at 15:01
  • For centering content vertically with pure CSS I found this too [under-voted Answer](http://stackoverflow.com/questions/388180/how-to-make-an-image-center-vertically-horizontally-inside-a-bigger-div/19206463#19206463). It works well also for older browsers. – try-catch-finally Jun 23 '14 at 20:15
  • @try-catch-finally Ok, I've managed to get that to work .... any idea how I would stop it from breaking when the content reaches 100% width? http://jsfiddle.net/pys3R/2/ (shrink the window until the text reaches the sides) – Lighty_46 Jun 24 '14 at 08:54

0 Answers0