1、我们可以利用"margin:0 auto"来设置元素水平居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.center{
margin:0 auto;
width:100px;
height:100px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="center"></div>
</body>
</html>
效果展示:2、利用text-align:center可以讲块级元素内的文字图片等水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.center{
text-align: center;
width:100%;
height:100px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="center">我想要居中</div>
</body>
</html>
效果展示:3、利用弹性布局:display:flex
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
width: 300px;
height: 300px;
background-color: aqua;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="container">
<div>111</div>
<div>222</div>
</div>
</body>
</html>
效果展示:
4、利用定位+margin:auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
position: relative;
width: 250px;
height: 250px;
background-color: aqua;
}
.container .test {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width:100px;
height:100px;
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="test"></div>
</div>
</body>
</html>
效果展示: