1. table
display: table;使父元素的作用像table元素一样,display: table-cell;使子元素的作用像td一样。给此时的子元素用vertical-align和text-align设置水平垂直居中,子元素其中的未知宽高的元素当然就相对子元素水平垂直居中了。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.table {
display: table;
}
.cell {
display: table-cell;
width: 100px;
height: 100px;
border: 1px solid #ccc;
vertical-align: middle;
text-align: center;
}
.cell span {
background: #ddd;
}
</style>
</head>
<body>
<div class="table">
<div class="cell">
<!--span是未知宽高,需水平垂直居中的元素-->
<span>hahaha</span>
</div>
</div>
</body>
</html>
2. JS计算
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.parent {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
position: absolute;
background: #ddd;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hahaha</div>
</div>
<script>
var child = document.querySelector('.child');
var parent = child.parentNode;
child.style.left = (parent.offsetWidth - child.offsetWidth) / 2 + 'px';
child.style.top = (parent.offsetHeight - child.offsetHeight) / 2 + 'px';
</script>
</body>
</html>
3. transform
transform:translate(tx[,ty])
定义2D转换。tx表示x方向偏移,ty表示y方向偏移。如果tx,ty为百分比的话,其参考值是元素本身的宽高,正适合未知宽高的居中定位。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.parent {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #ddd;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hahaha</div>
</div>
</body>
</html>
4. flexbox(弹性容器布局)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.parent {
display: flex;
justify-content: center; /* 设置弹性容器的item在主轴上居中 */
align-items: center; /* 设置弹性容器的item在交叉轴上居中 */
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
background: #ddd;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hahaha</div>
</div>
</body>
</html>
5. grid(网格布局)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.parent {
display: grid;
justify-items: center; /* 在行中的对齐方式 */
align-items: center; /* 在列中的对齐方式 */
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
background: #ddd;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hahaha</div>
</div>
</body>
</html>
网友评论