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

center div with position absolute

  • I have this markup for example :
    <div id="container">
    <div id="search">
    ----some content----
    </div>
    </div>

    and this css:
    #container {
    position:relative;
    width:100%;
    }
    #search {
    position:absolute;
    top:0;
    left:50%;
    }

    Am I forced to define the width of container in pixels to make the search be in the middle of the screen, because I want to be centered for almost every desktop resolutions?
  • use this trick

    .div-abc {position:absolute;
    z-index:1;
    width:500px; height:500px; background:#666; border:solid 1px #333;
    border-radius:10px;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    left:50%;
    margin-left:-250px;
    }
  • The div must have a fixed size to center an absolute div ( without js )
  • @jamy_za that depends on if you need it to work in IE7 or not. The link I posted above shows a solution that doesn't require a fixed width.
  • Oh yeah, this is the answer I was looking for, many thanks.
    But now I have another issue, I can't center some thumbnails vertically.
    I've tried to use : vertical-align: middle; but with no success.

    Markup for this is:
    <div id="tS1" class="jThumbnailScroller">

    <div class="jTscrollerContainer">
    <div class="jTscroller">

    <a href="#"><img src="thumbs/1.jpg" /></a>
    <a href="#"><img src="thumbs/2.jpg" /></a>
    .................

    </div>

    </div>


    </div>

    and this css:

    .jThumbnailScroller#tS1{
    position:relative;
    width:100%;

    }
    .jThumbnailScroller .jTscrollerContainer{position:absolute;}
    .jThumbnailScroller .jTscroller{position:relative; height:100%; margin:0; left:0; top:0; display:inline-block; *display:inline;}
    .jThumbnailScroller{
    position:relative;
    width:800px;
    height:255px; /*changed 255px set it if you change #tt margin-top value*/
    margin:0;
    padding:0;
    overflow:hidden;
    }



  • I'm not sure exactly what you're trying to do, but looking at the markup on this page might help: http://joshnh.com/lab/