欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

3种常见方法:使用CSS实现盒子的水平和垂直居中

最编程 2024-01-12 09:19:52
...
需要居中显示的子盒子
<body>
    <div class="box">我要居中显示</div>
</body>
 

一、子盒子拥有固定的长宽

1、绝对定位 + margin负间距

.box {
        background: red;
        width: 200px; 
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
    }

2、绝对定位 + margin:auto

.box {
        background: red;
        width: 200px; 
        height: 200px;
        position: absolute;
        top: 0;
 bottom: 0;
        left: 0;
 right: 0;
        margin: auto;
    }

二、子盒子没有固定的长宽

绝对定位 + transform:translate(x,y)

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

三、flex布局

父盒子定义flex布局,项目在主轴和交叉轴的对齐方式全部为  center

 <div class="fa">
        <div class="box">我要居中显示</div>
 </div>

 子盒子长宽可固定可不固定

 .fa{
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0;
        padding: 0;
    }
    .box {
        background: red;
        width: 200px; 
        height: 200px;
}
 

原文地址:https://www.cnblogs.com/ymbcc/p/14871037.html