<div class="parent">
<div class="child"></div>
<span>我是span</span>
</div>
1.行内块元素 display:inline-block元素,可以设置父元素 text-align:center
.parent{
background-color: aqua;
text-align: center;
}
.child{
width: 300px;
height: 200px;
background-color: blue;
}
span{
display: inline-block;
}
2.定宽的元素水平居中(1)
使用margin:0 auto 元素一定要有指定的宽度
.child{
width: 300px;
height: 200px;
background-color: blue;
margin: 0 auto;
}
3.定宽的元素水平居中(2)
对元素开启相对定位,使用left和margin-left
.child{
width: 300px;
height: 200px;
background-color: blue;
/* margin: 0 auto; */
position: relative;
left: 50%;
/* 为元素宽度的一半 */
margin-left: -150px;
}
效果与上图一样
4.定宽的元素水平居中(3)
子元素开启绝对定位,父元素开启相对定位,使用left,right,margin(根据水平排列的那个等式)
.parent{
background-color: aqua;
text-align: center;
position: relative;
height: 300px;
}
position: absolute;
right: 0;
left: 0;
margin: auto;
5.定宽的元素水平居中(4)
开启绝对定位和相对定位,使用left属性和transform属性
position: absolute;
left: 50%;
transform: translateX(-50%);
6.定宽的元素水平居中(5)
使用flex布局
.parent{
background-color: aqua;
text-align: center;
/* position: relative; */
height: 300px;
display: flex;
justify-content: center;
/* justify-content:space-between; */
}
7.定宽的元素水平居中(6)
使用Grid布局
.parent{
background-color: aqua;
text-align: center;
/* position: relative; */
height: 300px;
/* display: flex;
justify-content: center; */
/* justify-content:space-between; */
display: grid;
/* 方法一 */
justify-items: center;
/* 方法二 */
justify-content: center;
.child{
width: 300px;
height: 200px;
background-color: blue;
/* margin: 0 auto; */
/* position: relative;
left: 50%; */
/* 为元素宽度的一半 */
/* margin-left: -150px; */
/* position: absolute;
left: 50%;
transform: translateX(-50%); */
/* margin: auto; */
/* 方法三 */
margin: auto;