css中实现元素水平居中的方式有哪些
自定义两个盒子
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
所给的样式为
<style type="text/css">
.father{
width: 200px;
height: 200px;
background-color: pink;
}
.father .son{
width: 50px;
height: 50px;
background-color: red;
}
</style>
其产生的效果为
现在需要的是让红色正方形水平垂直居中
- 使用flex布局,justify-content: center; align-items: center;实现
如果不明白flex布局可以看一下这篇文章display:flex布局
<style type="text/css">
.father{
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: pink;
}
.father .son{
width: 50px;
height: 50px;
background-color: red;
}
</style>
- 使用绝对定位,然后上下左右的值设为0,margin为auto
在使用之前需要将父元素设置为相对定位
<style type="text/css">
.father{
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.son{
position: absolute;
top: 0;
bottom : 0;
left: 0;
right: 0;
margin: auto;
width: 50px;
height: 50px;
background-color: red;
}
</style>
- 绝对定位,设置left和top为50%,设置transform: translate(-50%,-50%);
<style type="text/css">
.father{
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.son{
position: absolute;
left: 50%;
top: 50%;
/*这个其实就是一个位移的属性,translateX在x轴方向上进行移动,反之translateY则是在y轴方向,而translate括号里的两个参数是先x后y的。*/
transform: translate(-50%,-50%);
width: 50px;
height: 50px;
background-color: red;
}
</style>
4.子元素display:inline-black,父元素上设置text-align:center
5.设置文本的话 行高+text-align
图中的1111处于水平居中
<style type="text/css">
.father{
position: relative;
width: 200px;
height: 200px;
text-align: center;
background-color: pink;
}
.son{
position: absolute;
left: 50%;
top: 50%;
/*这个其实就是一个位移的属性,translateX在x轴方向上进行移动,反之translateY则是在y轴方向,而translate括号里的两个参数是先x后y的。*/
transform: translate(-50%,-50%);
width: 50px;
height: 50px;
line-height: 50px;
background-color: red;
}
</style>