欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CSS2/CSS3盒子居中的三种方法

程序员文章站 2024-01-26 08:24:04
...

设计文稿:B在A的中间

CSS2/CSS3盒子居中的三种方法

1.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>盒子居中</title>
    <style>
        div{
            width:200px;
            height:200px;
            border:1px solid red;
            display:table-cell;
            text-align:center;
            vertical-align:middle;
        }
        div span{
            display:inline-block;
            width:100px;
            height:100px;
            border:1px solid black;
        }
    </style>
</head>
<body>
    <div>
        <span></span>
    </div>
</body>
</html>
2.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>盒子居中</title>
    <style>
        div{
            width:200px;
            height:200px;
            margin:100px auto;
            border:1px solid red;
            position: relative;
        }
        div span{
            display:block;
            width:100px;
            height:100px;
            border:1px solid blueviolet;
            position:absolute;
            top:0;
            left: 0;
            right: 0;
            bottom: 0;
            margin:auto;
        }
    </style>
</head>
<body>
    <div>
        <span></span>
    </div>
</body>
</html>
3.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>盒子居中g</title>
    <style>
        div{
            width:200px;
            height:200px;
            border:1px solid black;
            display:flex;
            flex-direction:row;
            justify-content: center;
            align-items: center;
            margin:100px auto;
        }
        div span{
            display:block;
            width:100px;
            height: 100px;
            border:1px solid pink;
        }
    
    </style>
</head>
<body>
    <div>
        <span></span>
    </div>
</body>
</html>