网页制作 
首页 > 网页制作 > 浏览文章

使用CSS实现盒子水平垂直居中的方法(8种)

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

原始代码:

center.html

<!DOCTYPE html>
<html lang="Zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Center</title>
    <link rel="stylesheet" href="center.css">
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>

</html>

center.css

body {
    background-color: #6ed0ff;
}

.father {
    background-color: #be33ec;
    border-radius: 20px;
    box-shadow: 0 0 15px rgb(0, 0, 0);
    margin: 100px auto;
    width: 300px;
    height: 300px;
}

.son {
    background-color: #fcff00;
    border-radius: 20px;
    box-shadow: 0 0 10px rgb(0, 0, 0);
    width: 100px;
    height: 100px;
}

原始效果:

使用CSS实现盒子水平垂直居中的方法(8种)

实现子盒子相对于父盒子垂直居中效果:

使用CSS实现盒子水平垂直居中的方法(8种)

1. grid

.father {
    display: grid;
}

.son {
    align-self: center;
    justify-self: center;
}

2. absolute + 负margin

.father {
    position: relative;
}

.son {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

3. absolute + transform

.father {
    position: relative;
}

.son {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

4. absolute + margin: auto

.father {
    position: relative;
}

.son {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

5. flex

.father {
    display: flex;
    justify-content: center;
    align-items: center;
}

6. margin+transfrom

.father {
    overflow: hidden;
}

.son {
    margin: 50% auto;
    transform: translateY(-50%);
}

7. table-cell

.father {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

.son {
    display: inline-block;
}

8. inline-block + vertical-align

.father {
    text-align: center;
    line-height: 300px;
}

.son {
    display: inline-block;
    vertical-align: middle;
}
上一篇:CSS3 按钮边框动画的实现
下一篇:纯 CSS 实现蜡烛融化(水滴)的示例代码
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网