常见的居中方式

如下代码:

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

  .father {
    width: 500px;
    height: 500px;
    background-color: aquamarine;
  }
  .son{
    width: 200px;
    height: 200px;
    background-color: burlywood;
  }

一:使用 Flexbox来实现

只需要修改 .father 样式便可实现

这样设置了 .father 为 Flex 容器,使用了 justify-content: center;align-items: center; 来使其中的子元素在水平和垂直方向上居中显示。


  .father {
    width: 500px;
    height: 500px;
    background-color: aquamarine;
    display: flex;
    justify-content: center;
    align-items: center;
  }

二:使用绝对定位实现

这里,通过设置 .father 为相对定位,然后使用绝对定位和 transform 属性让 .son 在父元素中上下左右居中。

.father {
  position: relative;
  width: 500px;
  height: 500px;
  background-color: aquamarine;
}

.son {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background-color: burlywood;
}

三:使用表格布局来实现

这种方法会将 .father 设置为表格单元格,并利用 vertical-align: middle;text-align: center; 让其中的子元素在水平和垂直方向上居中。

  .father {
    width: 500px;
    height: 500px;
    background-color: aquamarine;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: burlywood;
    display: inline-block;
  }

四:使用Grid来实现

这种方法使用了 Grid 布局的 place-items: center; 属性将子元素居中放置在父容器中

.father {
  width: 500px;
  height: 500px;
  background-color: aquamarine;
  display: grid;
  place-items: center;
}

.son {
  width: 200px;
  height: 200px;
  background-color: burlywood;
}

五:使用calc()函数来实现

这种方法利用 top: 50%;left: 50%;.son 元素的左上角定位在其父元素的中心,然后使用 transform: translate(-50%, -50%); 把元素自身向左上移动一半宽度和高度,使其居中显示。

.father {
  width: 500px;
  height: 500px;
  background-color: aquamarine;
}
.son {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background-color: burlywood;
}

六:使用Flexbox和margin:auto 来实现

在这个例子中,将 .father 设置为 Flex 容器并使用了 justify-content: center;align-items: center; 居中子元素。而 .son 中的 margin: auto; 则会自动将剩余空间均匀分配到元素的上下左右,实现了居中效果。

.father {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 500px;
  height: 500px;
  background-color: aquamarine;
}

.son {
  width: 200px;
  height: 200px;
  background-color: burlywood;
  margin: auto;
}

总结:这些方法都可以用来实现上下左右居中的效果,但它们的适用性和兼容性可能因浏览器和布局需求而异。在选择方法时,需要综合考虑你的布局要求和浏览器兼容性。第一种方法(Flexbox)和第二种方法(绝对定位)通常是最常用且最灵活的方式,但其他方法也可以根据具体情况提供一些替代选择。

当然还有和多种方法这里就不一一列举了,希望对大家有所帮助。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值