前端实现元素水平垂直居中的4种常用方式
方式一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素水平垂直居中</title>
</head>
<style>
#father{
width: 500px;
height: 500px;
background:blue;
position: relative;
}
#son{
width: 200px;
height: 200px;
background:gray;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
<body>
<div id="father">
<div id="son"></div>
</div>
</body>
</html>
方式二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素水平垂直居中</title>
</head>
<style>
#father{
width: 500px;
height: 500px;
background:blue;
position: relative;
}
#son{
width: 200px;
height: 200px;
background:gray;
position: absolute;
top: 50%;
left: 50%;
margin-left:-100px;
margin-top: -100px;
}
</style>
<body>
<div id="father">
<div id="son"></div>
</div>
</body>
</html>
方式三:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素水平垂直居中</title>
</head>
<style>
#father{
width: 500px;
height: 500px;
background:blue;
position: relative;
}
#son{
width: 200px;
height: 200px;
background:gray;
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%) /*向左移动宽度的50%,向上移动高度的50%*/
}
</style>
<body>
<div id="father">
<div id="son"></div>
</div>
</body>
</html>
方式四:设置父元素dispaly:flex,然后设置主轴和非主轴方向的子元素居中排布
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素水平垂直居中</title>
</head>
<style>
#father{
width: 500px;
height: 500px;
background:blue;
display: flex;
justify-content: center;
align-items: center;
}
#son{
width: 200px;
height: 200px;
background:gray;
}
</style>
<body>
<div id="father">
<div id="son"></div>
</div>
</body>
</html>
效果图: