中心Div在屏幕上

时间:2014-10-27 20:52:27

标签: html css center

.alert{
    color:#555;
    border-radius:10px;
    font-family:Tahoma,Geneva,Arial,sans-serif;font-size:11px;
    padding:10px 10px 10px 36px;
    margin:10px;
    min-width: 500px;
    position: fixed;
    display: block;
}

如何在不使用设定的起始宽度的情况下将其置于屏幕中心?

4 个答案:

答案 0 :(得分:1)

有很多方法可以使元素居中。在您的情况下,应用以下css:

.alert{
/*add this rules*/
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
/*upto this*/
  color:#555;
  border-radius:10px;
  font-family:Tahoma,Geneva,Arial,sans-serif;font-size:11px;
  padding:10px 10px 10px 36px;
  margin:10px;
  min-width: 500px;
  position: fixed;
  display: block;
}

另外,请看一下中心技巧herehere


你不应该记住的链接。只需谷歌关于centering tricks,然后你就会有很多关于它们的文章。请在下次提问之前进行研究。

答案 1 :(得分:0)

以下是如何做到这一点,添加:

.alert{
     top: 50%;
     left: 50%;   
     -webkit-transform: translate(-50%, -50%);
     -ms-transform: translate(-50%, -50%);
     transform: translate(-50%, -50%);
}

请在此处查看:JSFiddle

答案 2 :(得分:0)

margin:0 auto 0 auto;

使用此代码

答案 3 :(得分:-1)

使用父div包裹警报并将其设置为text-align: center;

<强> HTML

<div class="alert-wrap">
    <div class="alert">My Alert Message!</div>
</div>

然后将.alert设置为display: inline-block;并移除position: fixed;

<强> CSS

.alert-wrap {
    text-align: center;
}

.alert {
    color:#555;
    border-radius:10px;
    font-family:Tahoma,Geneva,Arial,sans-serif;font-size:11px;
    padding:10px 10px 10px 36px;
    margin:10px;
    min-width: 500px;
    display: inline-block;
}

工作示例: http://jsfiddle.net/tahrmzLz/