【CSS】div 盒子居中的常用方法-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
<body>
    <div class="main">
        <div class="box"></div>
    </div>
</body>
  1. 绝对定位加 margin: auto;
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .main {
        width: 400px;
        height: 400px;
        border: 2px solid #000;
        position: relative;
        margin: 30px auto;
    }
    .box {
        width: 100px;
        height: 100px;
        background-color: #f00;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
</style>
  1. 绝对定位加负 margin
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .main {
        width: 400px;
        height: 400px;
        border: 2px solid #000;
        position: relative;
        margin: 30px auto;
    }
    .box {
        width: 100px;
        height: 100px;
        background-color: #f00;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
    }
</style>
  1. margin 推动
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .main {
        width: 400px;
        height: 400px;
        border: 2px solid #000;
        margin: 30px auto;
    }
    .box {
        width: 100px;
        height: 100px;
        background-color: #f00;
        margin: 150px 150px;
    }
</style>
  1. flex 居中
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .main {
        width: 400px;
        height: 400px;
        border: 2px solid #000;
        margin: 30px auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .box {
        width: 100px;
        height: 100px;
        background-color: #f00;
    }
</style>
  1. transform
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .main {
        width: 400px;
        height: 400px;
        border: 2px solid #000;
        margin: 30px auto;
        position: relative;
    }
    .box {
        width: 100px;
        height: 100px;
        background-color: #f00;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
</style>
  1. 子盒子宽高不确定需要保证left和right的百分数一样top和bottom的百分数一样
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .main {
        width: 400px;
        height: 400px;
        border: 2px solid #000;
        margin: 30px auto;
        position: relative;
    }
    .box {
        background-color: #f00;
        position: absolute;
        left: 25%;
        top: 25%;
        right: 25%;
        bottom: 25%;
    }
</style>

<body>
    <div class="main">
        <div class="box"></div>
    </div>
</body>

在这里插入图片描述

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: CSS