将一个div水平垂直居中,并在调整父元素大小时保持其居中

20

我希望随时将一个div水平和垂直居中。

当我缩小或放大窗口的宽度时,div会始终保持在窗口的中心位置。

.cent
{
  height:50px;
  width:50px;
  background-color:black;
  margin:auto;
}

这里是我目前的JSFiddle示例

但我也想让这个div在纵向上保持居中,以便在缩小/增加窗口高度时,div会响应并保持在窗口中央。

关于这个示例,我希望能像水平居中一样,在窗口调整大小时,保持黑色框在垂直方向上居中。


请看这个链接:http://tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/ - Michael Unterthurner
@Aaron 你指的是哪个解决方案? - user123444555621
8个回答

37

您可以使用CSS表格来实现这一点:

JsFiddle

标记

<div class="container">
    <div class="cent"></div>
</div>

(相关的)CSS

    html,body
    {
        height: 100%;
    }
    body
    {
       display: table; 
       margin: 0 auto;
    }
    
    .container
    {  
        height: 100%;
        display: table-cell;   
        vertical-align: middle;    
    }
    .cent
    {
        height: 50px;
        width: 50px;
        background-color: black;      
    }

1
尝试这个。
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -25px;
    margin-top: -25px;

1

演示链接在这里


    .cent
    {
        height:50px;
        width:50px;
        background-color:black;
        margin:auto;
        position:absolute;
        left:50%;
        top:50%;
        margin-left:-25px;
        margin-top:-25px;
    }

0

测试一下

.cent {
    width: 50px;
    height: 50px;
    background-color: black;

    position:absolute;
    left:0; 
    right:0;
    top:0; 
    bottom:0;
    margin:auto;

    max-width:100%;
    max-height:100%;
    overflow:auto;
}

这里有一个例子:http://jsbin.com/iquviq/30/edit


当窗口垂直高度小于该div高度时,它将溢出页面顶部。 - MRC

0

请检查这个

 .cent
   {
      height:50px;
      width:50px;
      background-color:black;
      margin:auto;
      margin-top:50%;
   }

div现在比窗口中心低25像素。当窗口大小调整时,它不会产生Aaron想要的效果。当您将高度设置为500px时,您可以轻松地看到它。 - GreyRoofPigeon

0

试一下这个

http://jsfiddle.net/tVuS6/4/

      .cent
    {
    height:50px;
    width:50px;
    background-color:black;
    margin-left: -150px;
    margin-top: -150px;
   margin:auto;
    position:absolute;
    top:50%;
    left:50%;
    }

0
.cent
{
  height:50px;
  width:50px;
  background-color:black;
  position:absolute;
  left:50%;
  top:50%;
  margin: 0 auto;
}

0
通常情况下,margin: 0 auto; 可以实现水平居中,而 vertical-align: middle 可以实现垂直居中。我尝试了这种方法,但是没有起作用。
请尝试以下的 css
.cent {
    height: 50px;
    width: 50px;
    background: #222;
    position: absolute;
    margin: -50px 0 0 -50px;
    left: 50%;
    top: 50%;
}

JSFiddle中检查它。

要了解更多关于技巧的信息,请查看将元素居中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接