CSS盒子居中的几种方法

本文详细介绍了如何使用flex布局、transform+margin、transform+position、position+margin负间距和table-cell方法实现CSS盒子居中。通过实例演示,帮助理解并掌握不同场景下的居中技巧。
摘要由CSDN通过智能技术生成

学习笔记 CSS盒子居中的几种方法

<div class='boxA'>
  <div class='boxB'><div>
<div>

1:用flex布局实现盒子居中

.boxA {
  width: 200px;
  height: 200px;
  background-color: #000;
   /* 给父盒子添加flex布局 */
  display: flex;
 /* 主轴方向 垂直 从上往下 y轴 */
  flex-direction: column;
  /* 主轴居中 */
  justify-content: center;
  /* 侧轴居中 */
  align-items: center;
}
.boxB {
  width: 100px;
  height: 100px;
  background-color: red;
}

2:transfrom+margin

.boxA {
  width: 200px;
  height: 200px;
  background-color: #000;
  border: 1px solid #000;
}
.boxB {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-left: 50%;
  margin-top: 50%;
  transform: translate(-50%, -50%);
}

3: transfrom + position(position:relative / absolute)

.boxA {
 	width: 200px;
    height: 200px;
    background-color:#000;
    /*(relative)给父级盒子设置相对定位 */
    position: relative;
}
.boxB{
 	width: 100px;
    height: 100px;
    background-color: red;
    /* (absolute)给子盒子设置绝对定位*/
    position: absolute;
    /* 向右、向下移动父盒子的一半 (偏移量) */
    left: 50%;
    top: 50%;
    /* translate若使用百分比,是相对于自身的比例的位移 */
    transform: translate(-50%, -50%);
}

4:position + margin负间距

.boxA {
    width: 200px;
    height: 200px;
    background-color:#000;
    /*(relative)给父级盒子设置相对定位 */
    position: relative;
}
.boxB {
	width: 100px;
    height: 100px;
    background-color: red;
    /* (absolute)给子盒子设置绝对定位*/
    position: absolute;
    top: 50%;
    left: 50%;
    /*margin负间距 */
    margin-left: -100px;
    margin-top: -100px;
}

5:table-cell

.boxA {
    display: table-cell;
    vertical-align: middle;
    width: 200px;
    height: 200px;
    border: 10px solid #000;
    background-color: #000;
}
.boxB {
    width: 100px;
    height: 100px;
    background-color:red;
    margin: 0 auto;
}

今天就整理到这里啦,点个赞了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值