美文网首页
不定宽高水平垂直居中3种方式实现

不定宽高水平垂直居中3种方式实现

作者: 神秘者007 | 来源:发表于2018-04-18 08:49 被阅读58次

一.使用CSS3 transform
外层容器
position:relative
内层容器
transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>不定宽高水平垂直居中</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .outer{
            width: 300px;
            height: 300px;
            border: 1px solid red;
            position: relative;  //  核心
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: orange;
            position: absolute; //  核心
            top: 50%; //  核心
            left: 50%;  //  核心
            transform: translate(-50%,-50%);  //核心
        }
    </style>
</head>
<body>

    <div class="outer">
        <div class="inner"></div>
    </div>

</body>
</html>

二、flex布局
最简单的flex布局,外层容器加上如下样式即可
display: flex;
justify-content: center;
align-items: center;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>不定宽高水平垂直居中</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .outer{
            width: 300px;
            height: 300px;
            border: 1px solid red;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: orange;
        }
    </style>
</head>
<body>

    <div class="outer">
        <div class="inner"></div>
    </div>

</body>
</html>

三、利用table-cell
外层容器
display:table-cell;
text-align:center;
vertical-align:middle;
内部元素
vertical-align:middle;
display:inline-block;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>不定宽高水平垂直居中</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .outer{
            width: 300px;
            height: 300px;
            border: 1px solid red;
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: orange;
            vertical-align: middle;
            display: inline-block;
        }
    </style>
</head>
<body>

    <div class="outer">
        <div class="inner"></div>
    </div>

</body>
</html>

相关文章

网友评论

      本文标题:不定宽高水平垂直居中3种方式实现

      本文链接:https://www.haomeiwen.com/subject/czwmkftx.html