如何将一个盒子居中显示

基础代码
样式:

  .parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
        }
        
        .child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
        }

html代码:

 

设置盒子的位置

方法一、通过定位---父盒子相对定位,子盒子绝对定位,top为父盒子的50%(将整个子盒子看成一个点),移动父盒子的50%,相当于多移动子盒子宽度的50%,所以需要margin-top向上移动-50%

如何将一个盒子居中显示_第1张图片
image.png

.parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
            position: relative;
        }
 .child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -150px;
            margin-left: -150px;
        } 

方法二、通过margin:auto来实现---另一个display:inline-block;margin:0px auto可以实现按钮的水平居中

.parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
            position: relative;
        }
 .child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        } 

方法三、通过display:table-celll,来实现

.parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
            display: table-cell;   /*  display 当赋值为table-cell时,此元素会作为一个表格单元显示于th td */
            vertical-align: middle; /*  设置元素垂直对齐方式 */
             text-align: center;   /*  规定元素中文本的水平对齐方式*/ 
        }
  .child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
            display: inline-block;
        } 

方法四、弹性盒子来实现-display:flex

.parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
            display: flex;
            justify-content: center;  /*弹性盒子里边横轴对齐方式*/
            align-items: center;     /* 弹性盒子纵轴的对齐方式*/
        }
.child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
     }

方法五、通过就算直接通过margin来移动

.parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
        }
  .child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
            margin-top: 150px;
            margin-left: 150px;
        } 

方法六、使用cale来实现

.parent {
            height: 600px;
            width: 600px;
            border: 2px solid black;
            position: relative;
        }
    .child {
            height: 300px;
            width: 300px;
            background-color: chocolate;
            position: absolute;
            top: calc(150px);
            left: calc(150px);
        }

参考文章;https://www.cnblogs.com/gzy-tw/p/11205854.html

你可能感兴趣的:(如何将一个盒子居中显示)