一、行内元素设置水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.part1 {
text-align: center;
}
.inline {
display: inline;
}
</style>
</head>
<body>
<div class="part1">
<div class="inline">我是行内元素</div>
<div class="inline">我是行内元素</div>
<div class="inline">我是行内元素</div>
<div class="inline">我是行内元素</div>
</div>
</body>
</html>
结果图:
给行内元素的父元素设置 text-align: center;
二、行内块元素设置水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.part2 {
text-align: center;
}
.inline-block {
display: inline-block;
}
</style>
</head>
<body>
<div class="part2">
<div class="inline-block">我是行内块元素</div>
<div class="inline-block">我是行内块元素</div>
<div class="inline-block">我是行内块元素</div>
<div class="inline-block">我是行内块元素</div>
</div>
</body>
</html>
结果图:
给行内块元素的父元素设置 text-align: center;
三、块元素设置水平居中
3.1 方法一 给块元素设置 text-align: center;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
/* div本身就是块元素 */
text-align: center;
}
</style>
</head>
<body>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
</body>
</html>
结果图:
3.2 方法二 给块元素设置宽度,然后设置左右外边框为 auto ,再设置 text-align: center;
第一步:使块元素居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.part3 div {
/* 需要给块元素设置宽度 */
width: 300px;
/* 给块元素设置边框、背景色,直观展示 */
border: 2px dashed red;
background-color: rgb(243, 217, 217);
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div class="part3">
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
</div>
</body>
</html>
结果图:
第二步:使块元素中的文本居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.part3 div {
/* 需要给块元素设置宽度 */
width: 300px;
/* 给块元素设置边框、背景色,直观展示 */
border: 2px dashed red;
background-color: rgb(243, 217, 217);
margin-left: auto;
margin-right: auto;
text-align: center;
}
</style>
</head>
<body>
<div class="part3">
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
<div>我是块元素</div>
</div>
</body>
</html>
结果图: