在HTML中实现元素的垂直水平居中,在面试中经常遇到,总结一下实现方案
1.通过flex布局
在外层div中设置display:flex;并且将justify-content和align-items设置为center即可设置为垂直水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.outer{
width: 400px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
background-color: antiquewhite;
}
.inner{
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
2.通过绝对定位的方式实现垂直居中
在父元素上设置display:relative;在子元素上设置display:absolute;top:50%;left:50%;transform: translate(-50%,-50%)即可实现垂直水平居中(注意:top和left的值是子元素的左上角相对于父元素的位置确定的,如果不加transform: translate(-50%,-50%)会导致子元素的整个div不是居中显示的)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.outer{
width: 400px;
height: 400px;
position: relative;
background-color: aquamarine;
}
.inner{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: beige;
}
</style>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
3.通过display:grid方式实现居中布局
display:grid方式的垂直水平布局和flex布局很相似。在父元素上设置display:grid 并且将justify-content和align-items设置为center即可设置为垂直水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.outer{
width: 400px;
height: 400px;
display: grid;
justify-content: center;
align-items: center;
background-color: aqua;
}
.inner{
width: 100px;
height: 100px;
background-color: bisque;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
4.通过display:table-cell方式
在父元素上设置display:table-cell;vertical-align: middle;text-align: center;之后在子元素上设置display: inline-block;如果子元素上没有设置display: inline-block;则不会垂直水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.outer{
width: 400px;
height: 400px;
display: table-cell;
vertical-align: middle;
text-align: center;
background-color: aquamarine;
}
.inner{
width: 100px;
height: 100px;
display: inline-block;
background-color: bisque;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>