当我们页面布局的时候,通常需要把某一个元素居中,这一篇文章为大家介绍一下居中的几种方法,本人文笔有限,请见谅!
一.水平居中
行内元素水平居中的方法,我们使用text-align:center;
.box {
/* 给块元素设置宽高 */
width: 300px;
height: 50px;
background-color: orange;
/* 水平居中 */
text-align: center;
}
我是需要水平居中的文字
块元素水平居中的方法 1.margin(外边距)的方法来做,使用margin:0 auto;
.box {
/* 给块元素设置宽高 */
width: 300px;
height: 50px;
background-color: orange;
margin: 0 auto;
}
2.使用absolute加margin-left的方法
.box {
/* 给加一个绝对定位 */
position: absolute;
/* 向右百分之50 */
left: 50%;
/* 外边距再减自身宽度的一半 */
margin-left: -150px;
/* 给块元素设置宽高 */
width: 300px;
height: 50px;
background-color: orange;
}
3.使用absolute加transform
.box {
/* 给加一个绝对定位 */
position: absolute;
/* 向右百分之50 */
left: 50%;
/* 横向上向左移动自身宽度的一半 */
transform: translateX(-50%);
/* 给块元素设置宽高 */
width: 300px;
height: 50px;
background-color: orange;
}
4.flex弹性盒子方法
.father {
width: 400px;
height: 400px;
background-color: orange;
/* 给父级开启弹性盒子 */
display: flex;
/* 主轴对齐方式 */
justify-content: center;
}
.son {
width: 200px;
height: 200px;
background-color: pink;
}
二.垂直居中
行内元素垂直居中,使用line-height
.box {
width: 300px;
height: 50px;
background-color: orange;
/* 行高等于全部高度 */
line-height: 50px;
}
块元素垂直居中方法: 1.使用absolute加margin-top的方法
.boss {
position: relative;
width: 300px;
height: 200px;
background-color: pink;
}
.box {
/* 给加一个绝对定位 */
position: absolute;
/* 向下百分之50 */
top: 50%;
/* 外边距再减自身高度的一半 */
margin-top: -25px;
/* 给块元素设置宽高 */
width: 300px;
height: 50px;
background-color: orange;
}
2.flex方法
.father {
width: 400px;
height: 400px;
background-color: orange;
/* 给父级开启弹性盒子 */
display: flex;
/* 侧轴对齐方式 */
align-items: center;
}
.son {
width: 200px;
height: 200px;
background-color: pink;
}
3.使用absolute加transform
.boss {
position: relative;
width: 300px;
height: 300px;
background-color: pink;
}
.box {
/* 给加一个绝对定位 */
position: absolute;
/* 向下百分之50 */
top: 50%;
/* 横向上向上移动自身宽度的一半 */
transform: translateY(-50%);
/* 给块元素设置宽高 */
width: 300px;
height: 50px;
background-color: orange;
}
感谢大家的阅读,如有什么不对的地方,可以向我提出,感谢大家!