水平居中
CSS2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
height: 300px;
width: 500px;
background-color: blue;
}
.content1{
width: 10rem;
margin: 0 auto;
background-color: brown;
}
</style>
</head>
<body>
<div class="container">
<div class="content1">
使用margin: 0 auto 居中
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
height: 300px;
width: 500px;
background-color: rgb(22, 206, 135);
text-align: center;
}
.content1{
width: 10rem;
background-color: brown;
display: inline-block;
}
</style>
</head>
<body>
<div class="container">
<div class="content1">
使用text-align:center 居中
</div>
</div>
</body>
</html>
css3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
height: 300px;
width: 500px;
background-color: rgb(22, 206, 135);
display: flex;
justify-content: center;
}
.content1{
width: 10rem;
height: 10rem;
background-color: brown;
}
</style>
</head>
<body>
<div class="container">
<div class="content1">
使用flex居中
</div>
</div>
</body>
</html>
垂直居中
css2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
height: 300px;
width: 500px;
background-color: rgb(22, 206, 135);
display: table-cell;
vertical-align: middle;
}
.content1{
width: 100px;
height: 100px;
background-color: brown;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container">
<div class="content1">
使用flex居中
</div>
</div>
</body>
</html>
css3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
height: 300px;
width: 500px;
background-color: rgb(22, 206, 135);
display: flex;
align-items: center;
}
.content1{
width: 100px;
height: 100px;
background-color: brown;
}
</style>
</head>
<body>
<div class="container">
<div class="content1">
使用flex居中
</div>
</div>
</body>
</html>
除了flex以外的垂直水平居中的技巧都是属于css2的