【HTML】div居中显示

方法1:

复制代码
.parent {
          width:800px;
          height:500px;
          border:2px solid #000;
          position:relative;
}
 .child {
            width:200px;
            height:200px;
            margin: auto;  
            position: absolute;  
            top: 0; left: 0; bottom: 0; right: 0; 
            background-color: red;
}
复制代码

方法2:

复制代码
.parent {
            width:800px;
            height:500px;
            border:2px solid #000;
            display:table-cell;
            vertical-align:middle;
            text-align: center;
        }
        .child {
            width:200px;
            height:200px;
            display:inline-block;
            background-color: red;
        }
复制代码

方法3:

复制代码
.parent {
            width:800px;
            height:500px;
            border:2px solid #000;
            display:flex;
            justify-content:center;
            align-items:center;
        }
        .child {
            width:200px;
            height:200px;
            background-color: red;
        }
复制代码

方法4:

复制代码
.parent {
            width:800px;
            height:500px;
            border:2px solid #000;
            position:relative;
        }
        .child {
            width:300px;
            height:200px;
            margin:auto;
            position:absolute;/*设定水平和垂直偏移父元素的50%,
再根据实际长度将子元素上左挪回一半大小*/
            left:50%;
            top:50%;
            margin-left: -150px;
            margin-top:-100px;
            background-color: red;
        }
复制代码

 

posted on   梦琪小生  阅读(30910)  评论(3)    收藏  举报

编辑推荐:
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· 通过一个DEMO理解MCP(模型上下文协议)的生命周期
· MySQL下200GB大表备份,利用传输表空间解决停服发版表备份问题
· 记一次 .NET某固高运动卡测试 卡慢分析
· 微服务架构学习与思考:微服务拆分的原则
阅读排行:
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· .net clr 8年才修复的BUG,你让我损失太多了
· 一个神奇的JS代码,让浏览器在新的空白标签页运行我们 HTML 代码(createObjectURL
· 即时通信SSE和WebSocket对比
· 做Docx预览,一定要做这个神库!!
< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

导航

统计

点击右上角即可分享
微信分享提示