一、利用margin

将margin设置为:margin:auto

auto意为自动填充。程序会计算元素两边的边距剩余情况,然后将剩余的边距平均的分配到元素左右两边,从而使元素水平居中但是这样仅仅只能使元素在水平上居中,在垂直方向上任然没有被居中。

image-20220709164120998

若要利用margin使水平、垂直方向上都居中则可以设置子元素(被居中元素)为绝对布局,设置父元素为相对布局。

/* .box1为父元素
.box1-1为子元素 */
.box1 {
    position: relative;
  
    height: 200px;
    width: 200px;
    background-color: red;
}

.box1-1 {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;

    height: 140px;
    width: 140px;
    background-color: blue;
}

image-20220709164746423

绝对定位的元素的位置相对于最近的已定位祖先元素,如果元素没有已定位的祖先元素,那么它的位置相对于最初的包含块。所以在使用绝对定位时,为了避免元素乱跑,将其父元素设置为相对定位。

二、利用相对定位设置上下左右距离来实现

在相对定位中设置:

top:50%;

left:50%;

在理论上就可以使元素水平和垂直都居中,但是由于元素坐标判定点位于元素开始位置,而不是正中间,就导致出现下面这种情况

image-20220709165939523

可以看出仅仅只是黑色方块的起始位置被居中,而不是整体都居中。

可以使用transform: translate(-50%, -50%);

使元素整体沿x,y轴平移使其居中

/* .box2为父元素
.box2-1为子元素 */
.box2 {
    height: 200px;
    width: 200px;
    background-color: yellow;
}

.box2-1 {
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  
    height: 140px;
    width: 140px;
    background-color: black;
}

image-20220709170725647

三、通过弹性布局

display:flex;一个功能十分强大的布局方式。

flex的主要属性:

  1. flex-direction
  2. flex-wrap
  3. flex-flow
  4. justify-content
  5. align-items
  6. align-content

只需要将主轴和交叉轴都设置为居中,整个元素都会被居中

/* .box3为父元素
.box3-1为子元素 */

.box3 {
    display: flex;
    align-items: center;
    justify-content: center;
  
    background-color: orange;
    height: 200px;
    width: 200px;
}

.box3-1 {
    background-color: brown;
    height: 140px;
    width: 140px;
}

image-20220709171443694

最后修改:2024 年 05 月 12 日
如果觉得我的文章对你有用,请随意赞赏