HTML中标签的块级元素居中问题的解决方法?
1、首先,我们通过一段html代码来模拟块级元素需要居中的场景,代码如下:
<html>
<head>
<title></title>
</head>
<style>
.parent{
width:200px;
height:100px;
background: blue;
}
.sub{
width:50px;
height:50px;
background: white;
text-align: center;
}
</style>
<body>
<div class="parent">
<div class="sub">居中元素</div>
</div>
</body>
</html>


2、使用margin居中。只需要将需要居中div的水平margin设置auto就可以实现水平居中。我们值需要在上一个步骤css代码.sub段添加margin:0 auto;即可修改,代码如下:
.sub{
width:50px;
height:50px;
background: white;
margin:0 auto; //添加这行代码
text-align: center;
}


3、父级元素padding居中,我们可以在居中元素添加父级div通过计算使得白色div居中父级的padding值是多少就可以通过父级div的padding来居中。
<html>
<head>
<title></title>
</head>
<style>
.parent{
height:100px;
width: 200px;
background: blue;
}
.contain{
padding-left: 75px
}
.sub{
width:50px;
height:50px;
background: white;
text-align: center;
}
</style>
<body>
<div class="parent">
<!--为sub添加父级div-->
<div class="contain">
<div class="sub">居中元素</div>
</div>
</div>
</body>
</html>



4、使用相对定位居中,通过relative将需要居中的块级元素相对父级居中,通过需要计算需要居中的距离。
代码如下:
<html>
<head>
<title></title>
</head>
<style>
.parent{
height:100px;
width: 200px;
background: blue;
position: absolute;
}
.sub{
width:50px;
height:50px;
background: white;
text-align: center;
position: relative;
left: 75px;
}
</style>
<body>
<div class="parent">
<div class="sub">居中元素</div>
</div>
</body>
</html>

5、通过上面几个步骤操作,梳理一下块级元素居中几种方式:
1. 使用margin:0 auto;居中
2. 计算父级padding值进行居中
3. 使用相对定位居中。
