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  纯计算(不推荐)
⽗盒⼦宽度的⼀半减去⼦盒⼦宽度的⼀半 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%);
}
absolute relative⽅法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 = ElementById('parent');    let child = ElementById('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';
p = (parentH - childH) / 2 + 'px';
</script>
</body>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。