css垂直水平居中?

如何实现B在A中,垂直和水平方向都居中?
代码如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta charset="UTF-8"/>
    <title></title>
    <style>
        #A {
            position: relative;
            width: 500px;
            height: 500px;
            background-color: green;
        }

        #B {
            position: absolute;
            max-width: 300px;
            max-height: 300px;
            background-color: blue;
        }
    </style>
</head>
<body>


<div id="A">
    <div id="B">哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥
        哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥
        哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥
        哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥
        哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥
    </div>
</div>


</body>
</html>
阅读 6.4k
7 个回答

两种方法:

第一种:

#A {
            position: relative;
            width: 500px;
            height: 500px;
            background-color: green;
        }

        #B {
            position: absolute;
            max-width: 300px;
            max-height: 300px;
            background-color: blue;
            /* add */
            margin:auto;
            left:0;
            right:0;
            top:0;
            bottom:0;
        }

第二种:

#A {
            position: relative;
            width: 500px;
            height: 500px;
            background-color: green;
        }

        #B {
            position: absolute;
            max-width: 300px;
            max-height: 300px;
            background-color: blue;
            /* add */
            top:50%;
            left:50%;
            transform:translate(-50%,-50%);
        }

今天刚学到的一种比较简单的方法:父容器设置display: flex; 要居中的子元素设置margin: auto;即可。
本例中

#A {
        position: relative;
        width: 500px;
        height: 500px;
        background-color: green;
        /*add*/
        display: flex;
        display: -webkit-flex;
    }
#B {
        /*position: absolute;*/
        max-width: 300px;
        max-height: 300px;
        background-color: blue;
        /*add*/
        margin: auto;
    }

ps. IE下好像有问题...

        #A {
            position: relative;
            width: 500px;
            height: 500px;
            background-color: green;
        }

        #B {
            width: 50%;
            height: 50%;
            margin: auto;
            position: absolute;
            top: 0; left: 0; bottom: 0; right: 0;
            max-width: 300px;
            max-height: 300px;
            background-color: blue;
        }              
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题