简体   繁体   English

有没有办法可以使用css3 calc在屏幕中央放置一个对话框?

[英]Is there a way I can use css3 calc to place a dialog in the center of my screen?

I am trying to use the following: 我想使用以下内容:

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

CSS: CSS:

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

However it seems like the div is positioned not in the center of the viewport but in the center of the div that encloses it. 然而,似乎div不是位于视口的中心,而是位于包围它的div的中心。

How can I make it so the div is positioned in the center of the screen using calc ? 我怎样才能使用calc来将div放在屏幕的中心?

You can use new display: flex 您可以使用新的display: flex

CSS CSS

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

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


jsFiddle 的jsfiddle

Browser Support 浏览器支持

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

Why don't you use: 你为什么不用:

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

or: 要么:

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

why not use the top: 0; bottom: 0; left: 0; right: 0; 为什么不使用top: 0; bottom: 0; left: 0; right: 0; top: 0; bottom: 0; left: 0; right: 0; trick? 特技?

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

html: HTML:

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

CSS: 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;
}

I think you should use: 我认为你应该使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM