Search code examples
csshtmlcenter

How to use CSS to vertically center a form in a div


video.html

<!DOCTYPE html> 
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div class="headerBar">
           <div class="searchForm">
                <form id="search" action="" method="get" target="_blank">
                    <input id="vb_yt_search-term" name="search_query" type="text" maxlength="128" />
                    <select name="search_type">
                    <option value="sAll">All</option>
                    </select>
                    <input type="submit" value="Search" />
                </form>
            </div>
        </div>
    </body>
</html>

style.css

.headerBar {
    background-color: #f1f1f1;
    width: 100%;
    height: 44px;
    border: 0px;
    padding:0px;
    margin:0px;
    position:fixed;
    top:0;
    left:0;
}

.searchForm {
    text-align: center;
    border: 0px;
    width: 100%;
    vertical-align: middle;
    position: relative;
}

Code:

Here is the code for you to try.

Question 1:

How can I vertically center the form (TextBox, ComboBox, and Button) in the headerBar using CSS? I want to stick with <div> instead of <table> if at all possible. I want it to be centered dynamically, so that if the page is re-sized, it will re-center... basically it can't be hard coded in with px.

Question 2:

How can I add more elements, once again using the <div> tags so that the items will not be centered, but approximately 1/4 and 3/4 respectively. To give you an example, the top bar in the image is YouTube.com. The Second, is my code. I would like to place objects where the YouTube logo is. Example

Question 3: (bonus)

This is not important, only an extra. In the picture shown above, is it possible to get the exact search bar and search button onto my form, but allow it to have what ever functionality I want?


Solution

  • Question #1:

    Remove height from div.headerBar, this way it will size up with the inputs.

    If you want a height, then don't use height. Use line-height:

    div.headerBar { line-height: 44px; }
    

    Question #2:

    <div class="wrap">
        <div class="left"></div>
        <div class="mid"></div>
        <div class="right"></div>
        <div class="clear" />
    </div>
    
    
    .wrap { width: 100%; }
    .left { float: left; width: 25%; }
    .mid { float:left; width: 50%; }
    .right { float:left; width: 24%; }
    .clear { clear: both; }
    

    Check fiddle: http://jsfiddle.net/WHXnW/2/

    Updated fiddle: http://jsfiddle.net/WHXnW/4/

    Now this is closer to what you want. Just play around with the styles to get it just the way you want.