div居中的几种方式

方式一:flex 布局

复制代码
<style>
    .box {
        width: 200px;
        height: 200px;
        border: 1px solid blue;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .item {
        background: red;
    }
</style>
<div class="box">
    <div class="item">
        <h1 >宽高不定</h1>
    </div>
</div>
复制代码

方式二: Position + transform

复制代码
<style>
    .box {
        width: 200px;
        height: 200px;
        border: 1px solid blue;
        position: relative;
    }

    .item {
        background: red;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>
<div class="box">
    <div class="item">
        <h1>宽高不定</h1>
    </div>
</div>
复制代码

方式三:position + margin

复制代码
<style>
.box {
    width: 200px;
    height: 200px;
    border: 1px solid blue;
    position: relative;
}

.item {
    width: 50%;
    height: 50%;
    background: red;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
</style>
<div class="box">
    <div class="item">
        <h1>宽高不定</h1>
    </div>
</div>
复制代码

方式四: Grid布局

 

复制代码
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>三十课 - 利用grid布局实现元素水平垂直居中示例</title>
    <style>
        .parent {
            height: 140px;
            display: grid;
            align-items:center;
            border: 2px dashed #f69c55;
        }
        .child {
            margin:auto;
            padding: 20px;
            width:10rem;
            color: #fff;
            background: black;
        }
    </style>
</head>
<body>
<div class="parent">
    <div class="child">好的程序员能写出人能读懂的代码。</div>
</div>
</body>
</html>
复制代码

 

posted @   磊~~  阅读(743)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示