首页 > Web开发 > 详细

css实现盒子水平垂直居中--3种常用方法

时间:2021-06-10 15:18:09      阅读:14      评论:0      收藏:0      [点我收藏+]
需要居中显示的子盒子
<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;
}

 

 

 

 

css实现盒子水平垂直居中--3种常用方法

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!