- 绝对定位+margin负值
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
.container{
width: 300px;
height: 300px;
background-color: blanchedalmond;
position: relative;
}
.child{
height: 100px;
width: 100px;
position: absolute;
left: 50%;
top:50%;
margin-left: -50px;
margin-top: -50px;
background-color: lightcyan;
}
</style>
</head>
<body>
<div class="container">
<div class="child"></div>
</div>
</body>
</html>
- 绝对定位+margin:auto
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
.container{
width: 300px;
height: 300px;
background-color: blanchedalmond;
position: relative;
}
.child{
height: 100px;
width: 100px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background-color: lightcyan;
}
</style>
</head>
<body>
<div class="container">
<div class="child"></div>
</div>
</body>
</html>
- transform: translate
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
.container{
width: 300px;
height: 300px;
background-color: blanchedalmond;
position: relative;
}
.child{
position: absolute;
left: 50%;
top:50%;
transform: translate(-50%, -50%);
background-color: lightcyan;
}
</style>
</head>
<body>
<div class="container">
<div class="child">child</div>
</div>
</body>
</html>
- table布局
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
.container{
width: 300px;
height: 300px;
background-color: blanchedalmond;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child{
display: inline-block;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="container">
<div class="child">child</div>
</div>
</body>
</html>
- flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
.container{
width: 300px;
height: 300px;
background-color: blanchedalmond;
display: flex;
justify-content: center;
align-items: center;
}
.child{
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="container">
<div class="child">child</div>
</div>
</body>
</html>