05 Mar 08 _ Position a div element absolute and align it top center using CSS


By Katy
in BlogTorials

I recently ran across this positioning problem. I was setting up a site where I needed a div layer (nav element) to go inside a layer with 100% width. I needed to position the div absolute, top and also align it in the middle of the page (see Pasta Technology for demo). CSS doesn’t always behave like you expect it would. But in the event you were wondering how to align your div top and center, here is the solution.

Set your container element’s position as absolute with top as 0px, if necessary. Next give it a position of left: 50%. Give the div an appropriate width for its contents. Then set it up with a margin-left as the negative value of half of the width. See my example:

#headerInside {
       position:     absolute;
       top:          0px;
       left:         50%;/*some magic to align the element in the center;
       width:        1000px;
       margin-left:  -500px;/* half of the width */
}

Align Div Top & Center

You can also use the same principle if you want to align the element in the middle of the page vertically, by using top: 50%.

Spread the Word:
  • Slashdot
  • Digg
  • Facebook
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Technorati
  • NewsVine


29 Responses to “Position a div element absolute and align it top center using CSS”

  1. Lebnik Says:

    it work!!!

  2. Zafada Says:

    Thanks girlfriend.

    For some reason Dreamweaver gets moody. I can do everything the same EXACT way in two different test documents and when I switch to design view one would be centered differently than the other. And like I said, same exact code throughout the entirety of the document.

    I like your site, hopefully all is well.

    Check out my url if you’re interested at http://www.zafada.com

    I’ve been using alot of my time lately learning javaScript..

  3. Karl Says:

    Saves an unnecessary wrapper div, thanks for the info.

  4. Jordan Says:

    Wow! Saved me much hassle because the Zen Garden CSS project does not allow new Divs to be created.

    Thank you!

  5. peter Says:

    Works like a charm! Thanks!

  6. Guillaume Says:

    Simple and GREAT !

    Thank you :-)

  7. Michael Rajesh Says:

    Thanks dear. It had helped me a lot when i searched.

  8. Nathan Lester’s Portfolio » Blog Archive » Small Update Says:

    [...] I could get it to work in all major browsers except the dreaded IE.  Well, I stumbled across this link and it saved me from having many more headaches or completely ditching the idea I had.  The [...]

  9. flair Says:

    GREAT! It work! Thank you!

  10. Patrick Prekel Says:

    Thank you!

  11. Brad Frost Says:

    Thanks for this. It helped me out in a pinch.

  12. Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-04-16 Says:

    [...] Position a div element absolute and align it top center using CSS _ The Red Frog Blog _ AWP _ Web an… [...]

  13. Nick Weynand Says:

    Works well except for when the browser size is much smaller than you would like (say 800×600). Then the left side of your containing div gets lost to the left of the browser and there’s no way to scroll over there and see it.

  14. Nick Weynand Says:

    Here’s an alternative:

    #container {
    position:absolute;
    top:0;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
    width:960px;
    }

    By setting left and right to 0 it forces the edges of the container to find the edge of browser. Then margin auto forces the margin to find the width of the container, centering it.

    This eliminates the left side hiding behind the browser window.

  15. vicki Says:

    It works for me in all major browers. I’m very greatful for your efforts. I’ve been trying to figure out how to make my flash design top and center for a few days now. I don’t know about older browsers though. I have IE 8 so if it doesn’t work with older browser I won’tknow until I launch the site and try on other computers.

  16. Jamison Says:

    I just got this version to work…

    It needed a separate line for IE (padding Vs. margin)

    …silly browsers, CSS scripts are for kids.

  17. Charles Says:

    I have tried for a half a day to get the menu I designed to center. It is a js script menu. Using your way finally got me the results I wanted. Thanks so much

  18. Eric-from-Boston Says:

    quick google search landed me here and saved me without getting a headache for an answer….thanks!

  19. Daniel Pipitone Says:

    Sweet action. Thanks for the great tip.

  20. Jessica Says:

    Nick’s alternative with the margin-left & right to auto work great in Firefox… but I can’t get it to work in IE. Can someone help?

  21. hunterd Says:

    Thanks a lot to Nick Weynand who gives a solution to the problem side hiding!
    You are a hero!

  22. Nuno Says:

    I tried Nick Weynand’s way because i don’t know the dimensions of the divs (he specified a width but in my case I don’t, and it works). It worked great in FF but it won’t work on IE7. do anyone have a solution? thanks

  23. Jay Says:

    Thanks nick. Your code works great!

  24. Steve Says:

    thank you, thank you, thank you!!

  25. Carlos Says:

    Thnks a lot just what I was looking for

  26. egidiocs Says:

    … and…

    … if u need to align divs inside div on bottom-top-left-or-right, check this out!

    http://blog.davieschoots.nl/2009/04/27/align-one-div-in-another-div-on-bottom-top-left-or-right/

  27. MishaPowerauto Says:

    Я в твиттере я нашёл отдушину. Не подписываюсь на лытдыбровские блоги. а вот в твиттере с удовольствием всякого почитаю.
    blog.awpny.com – супер!!!!

  28. auctions Says:

    Very nice, this worked out great for us! Thanks for your help… keep up the great work…

  29. Xen Says:

    THANK YOU! Works a treat =]


Leave a Reply

  • guitar modification parts
  • butcher paper roll dispenser
  • makers of dog kennels
  • credit card debt relief program
  • billet grills
  • studio rta the bug computer desk
  • shark cordless cyclonic hand vacuum
  • toastmaster parts toaster
  • men's suits shirts barney
  • saucony shoes outlet stores
  • 1 2 decorative square post caps
  • fruit of the loom union suits
  • maine snowmobile insurance requirements
  • boyne mountain grand lodge and spa
  • triple pet natural toothpaste
  • used kids dirt bikes for sale
  • 30 inch slide in electric range
  • create pdf word embed fonts
  • wholesale jelly jars
  • water as fuel denny klein
  • couch replacement pillows
  • coleman bayside elite replacement parts
  • sponge bob crabby patty candy
  • wholesale winter gloves hats
  • best at home treatment for blackheads
  • tub refinishing pgh pa
  • tile shower seat vintage
  • caught wearing high heels split skirt
  • kawasaki kx85 parts and exploded view
  • india and business dress
  • kid's camp crafts
  • cuff bracelets wholesale
  • golf gps systems reviews
  • wholesale patio pool furniture
  • crystal on the plaza
  • global travel shoes
  • spectrum products tanning bed
  • 84 wide wooden window blinds
  • consigning my lilly pulitzer clothes
  • no smoking rooms in boston hotels
  • aubrey organics skin cleanser
  • home decor liquidators furniture and flooring
  • hair regrowth products reviews
  • black bean corn citrus vinegar
  • jt paintball gear
  • how to create finger nail designs
  • popup tent cleaning
  • knife sound editing
  • hippie chick costumes
  • miniature surveillance cameras detection
  • hd high def video edit
  • recycle styrofoam cups
  • bamboo patio door blinds
  • money order promise rings
  • resurfacing bathtubs
  • mens star earrings
  • spray face foundation
  • remote home thermostats
  • phoenix skin rejuvenation
  • shower enclosures walls
  • kawasaki 440 aircraft engine parts
  • women's clothing sleep shirts
  • material requirements planning mrp systems
  • cryoserver back email compliance archiving message
  • home flea infestation
  • cuisinart 9-speed hand mixer brushed chrome
  • wholesale military surgical caps
  • nike drawstring backpack lavender
  • acutane colon problems
  • mercedes 320 wagon tires
  • ucla womens basketball camps
  • vida international fruta
  • kids camp crafts
  • compliance corporate email
  • good feet store onalaska wi
  • coach purse party
  • women's shoulder handbags
  • diy exterior patio blinds
  • pivot tub shower enclosures
  • dog harness and collar
  • shoi racing helmets
  • free shawl knit patterns
  • thyme essential oil price
  • tubeless bicycle wheels road
  • black edition magazine man swimsuit
  • 5 star car wax
  • italian charm bracelets wholesale
  • sleep t shirts
  • audio cards upside down
  • dell 5100cn colour network laser printer
  • fj cruiser trailer hitch receivers
  • sell structured settlement payment
  • organizational monitor stands
  • prom decorations and costumes
  • cats on behavior medication
  • golf palm computer gps system
  • budget wedding planning checklist
  • movie theater popcorn maker canada
  • water pump 3-inch suction hose
  • invest in stocks cheap
  • nike max air inline skates
  • star wars galactic heroes bedding comforter
  • airsoft outfitters gear
  • cheap new chevy trucks
  • discounted airfares cheapest airfares erfurt
  • floral furniture throws
  • schutt baseball equipment
  • acrobat distiller settings for news print
  • 2.4 to 3.8 s10 truck conversion
  • westgate villia resorts
  • fuzzy bunny slippers adult
  • shock doctor mouth pieces
  • midwest family vacations
  • red kap highland uniform shirts
  • play euchre free online
  • rockport shoes rosemont
  • elo entuitive touchscreen drivers
  • decorative garden pond fountains
  • kids online cake decorating games
  • america west airlines dividend miles program
  • in kind giving from popcorn company
  • camera ccd industrial
  • outdoor furniture pool harrows
  • raymond waites spring garland
  • lil boosie new mixtapes
  • household and cleaning forum
  • video piggy 1.3.0 crack