Search code examples
cssalignmentcenter

CSS: Center block, but align contents to the left


I want a whole block to be centered in its parent, but I want the contents of the block to be left aligned.

Examples serve best

On this page :

http://yaml-online-parser.appspot.com/?yaml=%23+ASCII+Art%0d%0a---+%7c%0d%0a++%5c%2f%2f%7c%7c%5c%2f%7c%7c%0d%0a++%2f%2f+%7c%7c++%7c%7c__%0d%0a&type=python

the ascii art should be centered (as it appears) but it should line up and look like "YAML".

Or this :

http://yaml-online-parser.appspot.com/?yaml=%3f+-+Detroit+Tigers%0d%0a++-+Chicago+cubs%0d%0a%3a%0d%0a++-+2001-07-23%0d%0a%0d%0a%3f+%5b+New+York+Yankees%2c%0d%0a++++Atlanta+Braves+%5d%0d%0a%3a+%5b+2001-07-02%2c+2001-08-12%2c%0d%0a++++2001-08-14+%5d%0d%0a

the error message should all line up as it does in a console.


Solution

  • Reposting the working answer from the other question: How to horizontally center a floating element of a variable width?

    Assuming the element which is floated and will be centered is a div with an id="content" ...

    <body>
    <div id="wrap">
       <div id="content">
       This will be centered
       </div>
    </div>
    </body>
    

    And apply the following CSS

    #wrap {
        float: left;
        position: relative;
        left: 50%;
    }
    
    #content {
        float: left;
        position: relative;
        left: -50%;
    }
    

    Here is a good reference regarding that http://dev.opera.com/articles/view/35-floats-and-clearing/#centeringfloats