Pergunta

I want to both horizontally and vertically center a pair of inputs as part of a form to appear in the middle of a div. How do I go about properly doing this? I can only get them to be horizontally centered right now.

Here's the HTML:

<body>
    <div id='flightdates'>
        <div id='wrapper'>
            <form id='dates'>Departing:
                <input type='text' id='departing'>
                <br/>Returning:
                <input type='text' id='returning'>
            </form>
        </div>
    </div>
</body>

Here's the CSS:

#flightdates {
    height: 50px;
    background-color: yellow;
}
#wrapper {
    text-align: center;
    vertical-align: middle;
}
Foi útil?

Solução

They look horizontally centered - but if you're looking to also center them vertically, just add a single CSS definition:

#dates{
    line-height:50px;
}

Where line-height matches the height of #flightdates. Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

Outras dicas

Add a <br/> after the first input

Check the solution : http://jsfiddle.net/t6LWR/

DEMO

Use display:table & table-cell to create a table like layout. which support vertical align middle.

Here is the CSS:

#flightdates {
    height: 50px;
    background-color: yellow;
    display: table;
    width: 100%;
}
#wrapper {
    text-align: center;
    vertical-align: middle;
    display: table-cell;
}

Add line-height:50px; to #wrapper

#wrapper {
    text-align: center;
    vertical-align: middle;
    line-height:50px;
}

jsFiddle edxample

try this:

.className{
    width:300px;
    height:200px;
    position:absolute;
    left:50%;
    top:50%;
}

As per comment. The idea here is that the position must be set to absolute in order for the left and top to react properly. The percentage is actually NOT as simple as it seems. It doesn't take into account the width or height of the string that it's positioning. So it may still seem ot of place. You may have to tweek it a little.

If you mean you want to center the form both horizontally AND vertically, you can use the CSS transform trick:

#flightdates {
    height: 50px;
    background-color: yellow;
    position: relative;
}
#wrapper {
    display: block;
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%,-50%);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

http://jsfiddle.net/teddyrised/yYz6C/1/

In fact, the #wrapper is not necessary. You can take it out, and apply the style to the form element, too.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top