1. table
display: table;使父元素的作用像table元素一樣猜极,display: table-cell;使子元素的作用像td一樣中姜。給此時(shí)的子元素用vertical-align和text-align設(shè)置水平垂直居中,子元素其中的未知寬高的元素當(dāng)然就相對(duì)子元素水平垂直居中了跟伏。
<!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計(jì)算
<!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轉(zhuǎn)換。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; /* 設(shè)置彈性容器的item在主軸上居中 */
align-items: center; /* 設(shè)置彈性容器的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(網(wǎng)格布局)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.parent {
display: grid;
justify-items: center; /* 在行中的對(duì)齊方式 */
align-items: center; /* 在列中的對(duì)齊方式 */
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>