treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Centering vertically

  • I have a slider on my homepage and I want this slider to have full width but fixed height.

    So my slider have width:100% (so as the images) and overflow:hidden and my question is: how can I center vertically the images?

    Thanks in advance.
  • Several ways you can accomplish this.

    In this jsfiddle example, i used the position: absolute, with a top: 50% and a margin-top that has a negative -(height / 2)px

    On this site (http://blog.themeforest.net/tutorials/vertical-centering-with-css/) is an interesting article about it using several methods.

    I hope it is any help for your solution

    ~ Wouter
  • WJ... can I jump in here as I'm learning css. On your fiddle you write in the css... "div#container", why have not just written "#container" and applied that to the div, or does it do something else when written that way?

    thanks in advance

    steve
  • No problem stevedeer,

    If you write div#container, the style will only apply to the id container that belongs to a div. So let's say you use <table id="container"> the style wont be applied, because we wrote div#container and therefor made it a div only style.

    It's not at all required to do it this way, it's just a habit now and i find it easier ;)

    ~ Wouter
  • Thank you, this is a great resource. I'm still looking for the best way but I think this is all I need.
  • Have you read this article?
  • My problem is a little different because the image I want to center vertically I bigger in height than the container.

    Here's the example: http://imageshack.us/photo/my-images/526/exampleqf.jpg/

    So the blue area is the slider and the green is my images that can have the same or bigger height than the slider. What I want is not showing the top part of the image but the middle.

    But I will try that way too, Mottie. I already had read that article but didn't remembered. Thank you.
  • <div id="wrapper">

    <div id="slider">
    <!-- slider here -->
    </div>

    <div id="large-image">
    <img src="blah-blah.jpg" alt="Huatchuuu" />
    </div>

    </div> <!-- end wrapper -->


    #wrapper{
    width:500px;
    height:300px; /* create maximum height */
    position:relative; /* <-- important */
    }

    #slider{
    position:absolute;
    width:500px;
    height:200px; /* <-- 300-200 = 100 */
    top:50px; /* <-- see here (100/2) */
    left:0px;
    }

    #large-image{
    position:absolute;
    width:400px; /* <-- 500-400 = 100 */
    height:300px; /* same height with the wrapper */
    top:0px;
    left:50px; /* <-- see here (100/2) */
    }