Pregunta

I have a relatively div positioned on top of a fixed position div and I would like to vertically align this first div. Is there a way to do this? This is my current markup:

<div class="overlay">
    <div id="dialogInvoice">
        content
    </div>
</div>

The CSS:

.overlay {
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.5);
    position: fixed;
    z-index: 10;
}

#dialogInvoice {
    width: 390px;
    height: 722px;
    margin: 0 auto;
    padding-top: 28px;
    border-radius: 4px;
    background: #ffffff;
    position: relative;
}

Any suggestions on this? I did try the line-height method but this is apparently only working when using mere text.

¿Fue útil?

Solución

If your element does not have a fixed width or height then you can't use the other solutions without using javascript to calculate the values.

Here is an alternative.

#dialogInvoice {
    width: 390px;
    height: 722px;
    padding-top: 28px;
    border-radius: 4px;
    background: #ffffff;
    position: absolute;
    left:50%;
    top:50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

Otros consejos

what you need to add to your css of #dialogInvoice is

top: 50%;

and change the margin to

margin: 361px auto;

(361 is 722 / 2)

it will first push your container half way down the page and then push it back up the required value, which is exactly half of its height (361px)

here is a jsfiddle for better understanding.

This CSS may do what you require:

.overlay {
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.5);
    position: fixed;
    z-index: 10;
}

#dialogInvoice {
    margin: 0 auto;
    padding-top: 28px;
    border-radius: 4px;
    background: #ffffff;
    position: absolute;
    top: 100px;
    bottom:100px;
    left:100px;
    right:100px;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top