一、块级盒子居中
核心是把盒子左右外边距都设置为auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>块级盒子居中</title>
<style>
.block {
background-color: skyblue;
width: 500px;
height: 249px;
/* 方法一: */
margin-left: auto;
margin-right: auto;
/* 方法二: */
margin: auto;
/* 方法三: */
margin: 0 auto;
}
</style>
</head>
<body>
<div class="block"></div>
</body>
</html>
二、块级盒子内行内元素或行内块元素居中
行内元素或行内块元素水平居中对齐 ,只需要给他们的父亲添加text-align: center。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>块级盒子内行内元素或行内块元素居中</title>
<style>
.box1 {
background-color: skyblue;
width: 500px;
height: 248px;
margin: 0 auto;
margin-bottom: 20px;
text-align: center;
}
.box2 {
background-color: skyblue;
width: 500px;
height: 249px;
margin: 0 auto;
text-align: center;
}
/* 行内元素或行内块元素水平居中对齐 */
/* 只需要给他们的父亲添加text-align: center; */
</style>
</head>
<body>
<div class="box1">
<span>span行内元素</span>
</div>
<div class="box2">
<img src="images/police.jpg" width="150px">
</div>
</body>
</html>