Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

i just went through this myself. that will center the content horizontally, but only if you can declare the width. why can't i just say "use the width of the longest element in the div?" and if you want to center vertically, forget it. might as well use a <table> instead.

oh, this isn't the css-bashing thread? whoops.



Here you go. Should work in all browsers except IE7 and earlier.

You can add as many column divs as you like.

Note that the html { height:100% } is needed when in HTML5 mode.

  <!DOCTYPE HTML>
  <html>
    <head>
      <style type="text/css">
        html, body { height:100%; margin: 0 auto; }
        body { display: table; vertical-align: middle; }
        .column { display:table-cell; vertical-align: middle; }
        p { text-align: center; }
      </style>
    </head>
    <body>
      <div class="column">
        <p>holy cow!</p>
        <img alt="shock the monkey" src="http://i.imgur.com/Pt9Pd.jpg" />
        <p>it worked!</p>
      </div>
    </body>
  </html>


holy crap. that's pretty good, man! when i was trying to get this to work a couple of nights ago, i would have gladly given you a hundred bucks for that code snippet, just to make the pain go away.

i was afraid that your method would screw up <ul> lists the way most of my attempts did, where the bullets would wind up stuck to the left margin while the text strings are goofily centered in the middle, but no, your way presents lists properly as well.

your code snippet is going into production for my iphone card game, to replace this awful hacked-together menu i made:

http://www.platinumball.net/hearts/png/orig_help_large.png

thanks!


Glad you like it. :)

when i was trying to get this to work a couple of nights ago, i would have gladly given you a hundred bucks for that code snippet, just to make the pain go away.

If you like, feel free to give a shout-out to @jjs in your game's credits. :)




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: