css --- > [小结]让盒子水平垂直居中的解决方案

描述

  • 有如下模型,想办法让
<style>
	.box{
		width: 500px;
		height: 500px;
		background: skyblue;
	}
</style>
<div class="box">
	<div class="inner"></div>
</div>
  • 想办法让inner在box中水平垂直居中

方案1: 使用绝对定位

  • 让子盒子相对于父盒子绝对定位,
  • 然后距离 左/上 边50%,
  • 在将外边距设为盒子 宽/高 的一半
    代码如下:
.box{
  position: relative;
  width: 150px;
  height: 150px;
  background: skyblue;
}
.inner{
  position: absolute;
  width: 50px;
  height: 50px;
  left:  50%;
  top: 50%;
  margin-left: -25px;
  margin-top: -25px;
  background: lightcoral;
}

在这里插入图片描述

方案2: 使用transform

  • 上面需要手动移动子盒子的宽高,即每次都要计算子盒子的宽高/2,
  • 可以尝试使用CSS3的transform属性,将盒子在水平和垂直方向移动-50%
  • 代码如下:
.inner {
  position: absolute;
  width: 50px;
  height: 50px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: lightcoral;
}

在这里插入图片描述

方案3: margin…

  • 此方法比较奇怪…
  • 思路是利用绝对定位,让盒子的left top right bottom全部为0,然后设置margin为auto
  • 代码如下
.inner {
  position: absolute;
  width: 50px;
  height: 50px;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background: lightcoral;
}

在这里插入图片描述

方案4: 使用js

  • 使用js先获取父盒子的 宽/高
  • 在获取子盒子的宽高,然后使用绝对定位,将左边距设置为 (父盒子宽 - 子盒子宽) / 2
<script>
  var box = document.querySelector('.box')
  var inner = document.querySelector('.inner')
  // 父盒子 宽高
  var bW = box.offsetWidth
  var bH = box.offsetHeight
  // 子盒子 宽/高
  var iW = inner.offsetWidth
  var iH = inner.offsetHeight
  inner.style.position = 'absolute'
  inner.style.left = (bW - iW) / 2 + 'px'
  inner.style.top = (bH - iH) / 2 + 'px'
</script>

方案5: flex布局

  • 个人认为最简单最棒的一种布局
  • 只需设置父元素的布局为flex布局,然后设置 justify-contentalign-items属性
  • 代码如下:
<style>
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 150px;
  height: 150px;
  background: skyblue;
}
.inner {
  width: 50px;
  height: 50px;
  background: lightcoral;
}
</style>

方案6: table-cell

  • 思想是将子盒子变成文本的形式(inline-block)
  • 然后向控制文本水平垂直居中
<style>
  .box {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 150px;
    height: 150px;
    background: skyblue;
  }
  .inner {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: lightcoral;
  }
</style>
发布了228 篇原创文章 · 获赞 41 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/104239853