CSS实现盒子居中对齐的七种方法

5 篇文章 0 订阅
4 篇文章 0 订阅

初始化两个盒子

  <style>
    .parent {
      width: 500px;
      height: 500px;
      background-color: skyblue;
    }
    .child {
      width: 200px;
      height: 200px;
      background-color: pink;
    }
  </style>

<body>
  <div class='parent'>
    <div class='child'></div>
  </div>
</body>

方法1 定位 子绝父相

子绝父相

.parent {
  position: relative;
}

.child {
  position: absolute;
}

方法1.1 margin 纯计算(不推荐)

父盒子宽度的一半减去子盒子宽度的一半 500/2 - 200/2 = 150
父盒子高度的一半减去子盒子高度的一半 500/2 - 200/2 = 150

.child {
  margin-top:150px;
  margin-left:150px;
}

方法1.2 margin设置为auto

.child {
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  margin: auto;
}

方法1.3 transform 

.child {
  position: absolute;
  top: 50%;
  left: 50%
}

再让子盒子往“回”移动自己宽高的一半

.child {
  transform: translate(-50%, -50%);
}

 

方法2 flex(推荐)

将父盒子设置成弹性盒容器
让子元素水平居中,垂直居中

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

 

方法3 table-cell 

.parent {
    display: table-cell;
    vertical-align: middle;
}

设置子盒子水平居中

.child {
  margin: 0 auto;
}

 

方法4 inline-block

子盒子设置成行内块

.child {
  display: inline-block;
}

 给父盒子添加

* text-align: center; 只对行内元素和行内块元素有用

.parent {
  text-align: center;
  line-height: 500px;
}

再给子盒子添加

.child {
  vertical-align: middle;
}

 

方法5 JavaScript

给盒子来个id,然后开始写js代码

  <style>
    .parent {
      width: 500px;
      height: 500px;
      background-color: skyblue;
    }
    .child {
      width: 200px;
      height: 200px;
      background-color: pink;
    }
  </style>

<body>
  <div class='parent' id='parent'>
    <div class='child' id='child'></div>
  </div>
  <script>
    let parent = document.getElementById('parent');
    let child = document.getElementById('child');
    let parentW = parent.offsetWidth;
    let parentH = parent.offsetHeight;
    let childW = child.offsetWidth;
    let childH = child.offsetHeight;
    parent.style.position = "relative"
    child.style.position = "absolute";
    child.style.left = (parentW - childW) / 2 + 'px';
    child.style.top = (parentH - childH) / 2 + 'px';
  </script>
</body>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值