使一个div居中显示的三种方法
1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div居中</title>
<style>
/*第一种方法*/
div{
width: 200px;
height: 200px;
background-color: orchid;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div居中</title>
<style>
/*第二种方法*/
div{
width: 200px;
height: 200px;
position: absolute;
background-color: orchid;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
使div2在div1里面居中显示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div居中</title>
<style>
/*第三种方法*/
#div1 {
width: 700px;
height: 600px;
background-color: orange;
display: flex;
align-items: center;
justify-content: center;
}
#div2 {
width: 200px;
height: 200px;
background-color: orchid;
}
</style>
</head>
<body>
<div id="div1">
<div id="div2"></div>
</div>
</body>
</html>