一个盒子水平垂直居中的7种方法

75 阅读1分钟

1.使用css的position属性和margin:auto

body {
  margin: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.centered-box {
  width: 200px;
  height: 200px;
  background-color: lightgray;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

2.利用css3的新增属性display:table-cell

body,html{
  height: 100%; 
  margin: 0; 
  display: table;
}
body {
  display:table-cell;
  vertical-align: middle;
  text-align: center;
}

.centered-box {
  width: 200px; 
  height: 200px; 
  background-color: lightgray; 
  margin: auto;
}

3.利用flexbox布局

body {
  height: 100vh; 
  margin: 0; 
  display: flex; 
  align-items: center;
  justify-content: center;
}

.centered-box {
  width: 200px; 
  height: 200px; 
  background-color: lightgray;
}

4.利用position和margin-left属性

body {
 height: 100vh; 
 margin: 0; 
 position: relative;
}

.centered-box {
  width: 200px;
  height: 200px; 
  background-color: lightgray; 
  position: absolute; 
  top: 50%;
  left: 50%;
  margin-top: -100px; /* 垂直方向上的负margin为元素高度的一半 */
  margin-left: -100px; /* 水平方向上的负margin为元素宽度的一半 */
}

5.利用position和transform属性

body {
 height: 100vh; 
 margin: 0; 
 position: relative;
}

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

6.使用grid布局实现上下左右居中

body `{`
 height: 100vh;
 margin: 0; 
 display: grid; 
 place-items: center;
}

.centered-box {
  width: 200px; 
  height: 200px;
  background-color: lightgray;
}

7.使用js原生

body {
  height: 100vh;
  margin: 0;
}

.centered-box {
  width: 200px; 
  height: 200px;
  background-color: lightgray;
  position: absolute;
}



<div class="centered-box" id="myBox">
    <!-- Your content goes here --> 
</div>
<script> 
    // 获取元素 
    var box = document.getElementById('myBox'); 

    // 计算居中位置 
    var leftPos = (window.innerWidth - box.offsetWidth)/ 2; 
    var topPos = (window.innerHeight - box.offsetHeight) / 2;

    // 设置样式 
    box.style.left = leftPos + 'px'; box.style.top = topPos + 'px'; 
</script>