如何让那个wrapper水平居中垂直居中

很简单的布局

<html>
<head>
    <style type="text/css">
        div.wrapper{
            width:1000px;
            height:500px;
            border:2px solid red;
            }
    </style>
</head>
<body>
    <div class="wrapper">
    <div>
</body>
</html>

div里面的内容省略了,如何将这个div.wrapper对html水平且垂直居中?

图片描述

我要这样的效果

图片描述

解决了水平居中,没有解决垂直居中。

<html>
<head>
    <style type="text/css">
        div.wrapper{
            width:1000px;
            height:500px;
            border:2px solid red;
            margin:0 auto;
            }
    </style>
</head>
<body>
    <div class="wrapper">
    <div>
</body>
</html>

阅读 5.8k
6 个回答
.wrapper {
   position:absolute;
   top:0;
   left:0;
   right:0;
   bottom:0;
   margin:auto;
}

方法很多的,加个 margin:0 auto; 就可以了。

涉及知识点:

水平居中

1、margin的计算:margin-left,margin-right,设置为auto,则会由浏览器自动计算,此时子节点margin-left === 子节点margin-right === (父节点width - 子节点width)/2,所以就是水平居中的效果。你设置margin:0 auto,只能水平居中。

水平垂直居中

1、margin负值的特性:margin-top、margin-left的值为负时,margin-top会是元素向上移动 |margin-top|(绝对值),margin-left会使元素向左移动 |margin-left|(绝对值)
2、position和top、left的特性:
(1)设置postion:absolute,会使得元素相对于离其最近的设置postion(非static)的祖先元素进行定位,该祖先元素设为ancestors;
(2)top设置为50%,意为ancestors的height的50%,设此值为fromTop;left设置为50%,意为ancestors的width的50%,设此值为fromLeft;代表该元素距离acestors的content的上边界fromTop,距离acestors的content的左边界fromLeft。
3、利用margin负值特性和position,left,top特性,这样就形成了垂直水平居中的效果。
4、兼容性问题:margin负值,具有兼容性问题。需要给其acestors设置overflow:hidden。

代码:

.wrapper{
    width:1000px;
    height:500px;
    border:2px solid red;
    /* 垂直水平居中 */
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -250px;
    margin-left: -500px;  
}

方案好多啊,flex布局比较简单易懂

<div class="box">
    <div class="wrapper"><div>
</div>
.box {
    display: flex;
    justify-content: center;
    align-items: center;
}

具体可以参考下:http://www.cnblogs.com/coco1s...

考虑兼容性的话还是JavaScript控制比较安全

新手上路,请多包涵

是他们想复杂了,还是我想的太简单。

margin top left各百分之五十 再负方向各移动div的二分之一宽高不就可以了吗。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题