当居中 div 宽度不固定时
1. 设置左右外边距值相等
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.parent {
width: 200px;
height: 300px;
background: #f60;
border:7px solid black;
}
.child {
outline:5px solid green;
margin-left:20px;
margin-right:20px;
text-align:center;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
当居中 div 宽度固定时
1. 设置左右外边距值为auto
margin: 0 auto;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.parent {
width: 200px;
height: 300px;
background: #f60;
border:7px solid black;
}
.child {
outline:5px solid green;
width:100px;
margin: 0 auto;
text-align:center;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
2. 行内元素 + text-align
.parent {
text-align:center;
}
.child {
display:inline-block;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.parent {
width: 200px;
height: 300px;
background: #f60;
border:7px solid black;
text-align:center;
}
.child {
display:inline-block;
outline:5px solid green;
width:100px;
height:100px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
网友评论