CSS实现盒子居中对齐的七种方法
CSS实现盒子居中对齐的七种方法
初始化两个盒子
<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>