css3 - css垂直水平居中?
PHP中文网
PHP中文网 2017-04-17 11:06:33
0
7
787

如何实现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>


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


</body>
</html>
PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(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%);
        }
洪涛

雷雷

http://jsfiddle.net/7uakz7p1/

阿神

今天剛學到的一種比較簡單的方法:父容器設置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下好像有問題...

PHPzhong

雷雷

Peter_Zhu

正好發現一個網站,給了好多解決方案 Centering in CSS: A Complete Guide

小葫芦

http://jsfiddle.net/nbayw7ea/

阿神

http://css-tricks.com/centering-css-complete-guide/

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板