一、元素垂直居中
- 不知道自己高度和父容器高度的情况下:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.father {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="father">
<div class="child">
我是child
</div>
</div>
</body>
</html>
- 父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.father {
height: 200px;
background: #333;
}
.child {
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="father">
<div class="child">
我是child
</div>
</div>
</body>
</html>
- flex方法
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.father {
display: flex;
flex-direction: column;
align-items: center; // 垂直居中
justify-content: center; // 水平居中
height: 200px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">
我是child
</div>
</div>
</body>
</html>
- 使用table-cell
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.father {
display: table-cell;
vertical-align:middle;
height: 200px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">
我是child
</div>
</div>
</body>
</html>
二、元素水平居中
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.father {
margin: auto;
width: 200px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">
我是child
</div>
</div>
</body>
</html>
网友评论