... <...">

Is it possible to use css3 calc to place the dialog in the center of the screen?

I am trying to use the following:

<div class="center">
  ...
</div>

CSS

.center{
    position: absolute;
    height: 50px;
    width: 50px;
    background:red;
    top:calc(50% - 50px/2);
    left:calc(50% - 50px/2);
}

However, it seems that the div is not located in the center of the viewport, but in the center of the div that surrounds it.

How can I make the div fit in the center of the screen using calc?

+4
source share
4 answers

why not use the trick top: 0; bottom: 0; left: 0; right: 0;?

http://jsfiddle.net/3n1gm4/WpYHS/

HTML:

<div class="centered">
    <h1>Perfectly Centered</h1>
    <h3>This is centered top to bottom and left to right</h3>
</div>

CSS:

.centered {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 50%; /* any width */
    height: 30%; /* any height */
    margin: auto;

    text-align: center;

    background: #deface;
}
+2
source

You can use new display: flex

CSS

#overlay {
    height: 100%;
    width: 100%;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

.dialog {
    margin: auto;
    width: 280px;
}


jsFiddle

Browser support

Firefox, Safari 6, IE 11 (maybe 10), Opera, Chrome

+5
source

:

.center {
    position: absolute;
    height: 50px;
    width: 50px;
    background: red;
    top: calc(50% - 25px);
    left: calc(50% - 25px);
}

.center {
    position: absolute;
    height: 50px;
    width: 50px;
    background: red;
    margin-top: -25px;
    margin-left: -25px;
    top: 50%;
    left: 50%;
}
+2

, :

.center {
    float: none;
    margin-left: auto;
    margin-right: auto;
}
0

All Articles