Search code examples
htmlcssalignmentcenter

Center aligning two elements wrapped in a div


I'm trying to center a div that contains two elements. Usually what I'd do is set a width then use margin: 0 auto; but in this case, that doesn't apply because I don't know the combined width of both the textbox and submit button (horizontally adjacent) with all the padding and margins and what not.

So basically I have in pseudo-html:

<div class="search">
    <input id="query"><button id="searchSubmit">
</div>

Is this possible? If so, how?

Not working demo: http://jsfiddle.net/6B9DT/

Thanks!


Solution

  • Using text-align: center; is usefull in such cases...here is a DEMO

    HTML

     <div class="search">
        <input id="query"> 
        <button id="searchSubmit">Search</button>
     </div>
    

    CSS

     body {
        text-align: center;
    }
    #search {
        text-align: left;
        border: 1px solid red;
        display: inline-block;
        /* for ie6/7: */
        *display: inline;
    
    }
    

    Please note that here text-align: center; has been given on body tag, it can be given to any parent wrapper of this search markup.