日常会用到,面试也会考到~
# 0. 初始化两个盒子
<style>
.parent {
width: 500px;
height: 500px;
background-color: skyblue;
}
.child {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<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
.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%);
}
【CSS】定位--静态定位-相对定位-绝对定位-子绝父相-固定定位-粘性定位 (opens new window)
# 方法2 flex(推荐)
将父盒子设置成弹性盒容器 让子元素水平居中,垂直居中
.parent {
display: flex;
justify-content: center;
align-items: center;
}
【CSS】flex布局-弹性盒-伸缩盒-代替浮动 (opens new window)
# 方法3 table-cell
.parent {
display: table-cell;
vertical-align: middle;
}
设置子盒子水平居中
.child {
margin: 0 auto;
}
# 方法4 inline-block
子盒子设置成行内块
.child {
display: inline-block;
}
给父盒子添加
.parent {
text-align: center;
line-height: 500px;
}
再给子盒子添加
.child {
vertical-align: middle;
}
# 方法5 JavaScript
给盒子来个id
<style>
.parent {
width: 500px;
height: 500px;
background-color: skyblue;
}
.child {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class='parent' id='parent'>
<div class='child' id='child'></div>
</div>
</body>
写js
<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>