常用盒子居中的的几种方法

323 阅读2分钟

大家应该都知道盒子最常用的的居中方法是margin: 0 auot 吧. 其实还有几种方法,让我来给大家一一介绍吧.

 大家好,大家一起学习,这是我第一次写博客,希望大家多多指点,多多指教,我把今天所学到的知识分享一下

第一种是使用我们的定位居中.

这个方法就是配合用定位配合margin来写,先用创建一个父级盒子和一个子级盒子, 然后分别给出宽高 代码如下: HTML样式

<div class="father">
    <div class="son"></div>
  </div> 

css样式:

   .father{
    position: relative;
    width: 400px;
    height: 400px;
    background-color: pink;
  }
  .son{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background-color: skyblue;
  }

这里面我们先让子级盒子定位到父级的50%,然后在给一个margin-top 和margin-left给子级自身盒子的宽高负的一半.

第二种方法就是使用变形方法来居中更方便

也就是transform: translate(x,y);

<div class="father">
    <div class="son"></div>
  </div>

css样式:

.father {
    position: relative;
    width: 500px;
    height: 500px;
    background-color: pink;
    margin: 100px auto;
}

.son {
    position: absolute;
    top: 50%;
    left: 50%;
    /* 百分比,往上走盒子自己高度的一半,往左走盒子宽度的一半 */
    **transform: translate(-50%, -50%);**
    /*注意:移动的时候可以写百分比,如果使用的百分比,移动的是盒子**自身的宽度** */
    width: 199px;
    height: 199px;
    background-color: skyblue;
}

里面打* 号的代码也就是这样给百分比的代码也就更方便以后如果更改盒子大小也就不用像上一种方法那样要计算子级的大小去除了复杂的步骤.

注意: margin移动盒子影响其余的盒子。把其他人挤走。 - 位移translate移动盒子不会影响其他的盒子。不脱标。

3.最后一种方法也就是我自己独创的摸索的方法

也是使用定位,但是给他的所有偏移值都为0 然后在使用margin. 如下:

盒子居中方法2.png

好了,这就是我的分享了,大家还有让盒子居中的方法可以在评论区留言,大家一起学习,这也是我第一次写博客,希望大家多多指点.