div居中方法总结

本文总结了多种使用CSS实现div元素水平及垂直居中的方法,包括利用margin、position、transform属性以及flex布局等,适用于不同场景的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

         在日常开发过程中,我们会经常使用到div居中来处理布局,今天我就把我在开发过程中,遇到的div居中处理方法总结一下,方便日后查看!

          

       1、 水平居中:给div设置一个宽度,然后添加margin:0 auto属性  
 
 
 div{
            margin:0 auto;
            width:200px;
            height:200px;
            background-color: pink;
        }

 

   

         2、水平垂直居中之让绝对定位的div居中

    div {
            position: absolute;
            width: 300px;
            height: 300px;
            margin: auto;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: pink;    
        }

   

         3、水平垂直居中之确定容器的宽高

 

div {
            position: absolute;
            width:300px;
            height:300px;
            top: 50%;
            left: 50%;
            margin: -150px 0 0 -150px;  /* 外边距为自身宽高的一半 */
            background-color: pink;
        }

 

 

        4、水平垂直居中之未知容器的宽高,利用 `transform` 属性 
 
  div {
            position: absolute;
            width:300px;
            height:300px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: pink;
        }

 

         5、水平垂直居中之利用 flex 布局

 

.container {
            display: flex;
            align-items: center;         /* 垂直居中 */
            justify-content: center;    /* 水平居中 */
            height:600px;

           }
.container div {
                width: 300px;
                height: 300px;
                background-color: pink;    
              }

 

           6、div撑满整屏

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>div撑满整屏</title>
  <style>
    .page{
      background:pink;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      position: absolute;
      text-align: center;
    }
  </style>
</head>
<body>
   <div class="page"></div>
</body>
</html>

 

 

 

 

 

 

转载于:https://www.cnblogs.com/chenyablog/p/6610241.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值