盒子水平垂直居中布局(总结)

目录

1.flex布局

2. inline-block(垂直居中时只是近似,不够精确!!!)

3. 绝对定位 + 2D转换

4. 绝对定位 + margin: auto

5. table


1.flex布局

.box {
  margin: 100px auto;
  width: 300px;
  height: 300px;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}
.child {
  width: 50px;
  height: 50px;
  background-color: pink;
}
    <div class="box">
        <div class="child"></div>
    </div>

2. inline-block(垂直居中时只是近似,不够精确!!!)

.box {
  margin: 100px auto;
  width: 300px;
  height: 300px;
  border: 1px solid black;
  text-align: center;
  line-height: 300px;
}
.child {
  display: inline-block;
  width: 50px;
  height: 50px;
  background-color: pink;
  vertical-align: middle;
}
    <!-- 
        给child设置display: inline-block;把child变成行内块盒子,就可以当做img标签设置text-align: center;水平居中
        然后给父盒子加行高line-height: 300px;子盒子基线对齐
     -->
    <div class="box">
        <div class="child"></div>
    </div>

3. 绝对定位 + 2D转换

        .box {
            position: relative;
            margin: 100px auto;
            width: 300px;
            height: 300px;
            border: 1px solid black;
        }
        .child {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 50px;
            height: 50px;
            background-color: pink;
        }
    <div class="box">
        <div class="child"></div>
    </div>

4. 绝对定位 + margin: auto

只想水平居中 right:0; left: 0;

        .box {
            position: relative;
            margin: 100px auto;
            width: 300px;
            height: 300px;
            border: 1px solid black;
        }
        .child {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            width: 50px;
            height: 50px;
            background-color: pink;
        }
    <div class="box">
        <div class="child"></div>
    </div>

5. table

只想水平居中 child里面的margin: 0 auto;去掉

.box {
  margin: 100px auto;
  width: 300px;
  height: 300px;
  border: 1px solid black;
  display: table-cell;    //表格里面的小方格
  vertical-align: middle;  //不能用于块级元素,只能作用于行内元素和行内块.在这里比较特殊.
}
.child {
  margin: 0 auto;
  width: 50px;
  height: 50px;
  background-color: pink;
}
    <!-- 
        父盒子为什么会跑呢?
        display: table-cell;设置之后父盒子已经不是块元素了,所以margin: 100px auto;失效了
     -->
    <div class="box">
        <div class="child"></div>
    </div>

猜你喜欢

转载自blog.csdn.net/weixin_46413834/article/details/125999886