行内元素与块级元素的水平垂直居中,有很多种方式,以下是我喜欢用的方式;
一、 水平居中
行内元素
.parent {
text-align: center;
}
块级元素
margin方式:
.son {
margin: 0 auto;
}
flex布局
.parent {
display: flex;
justify-content: center;
}
绝对定位
.son {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
二、垂直居中
行内元素
.parent {
height: 高度;
}
.son {
line-height: 高度;
}
/* 注:① 子元素 line-height 值为父元素 height 值。② 单行文本。 */
块级元素
flex弹性盒子
.parent {
display: flex;
align-items: center;
}
绝对定位
.son {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
小案例:
盒子box1里面的盒子box2,需要水平居中;
box2中的文字,需要水平垂直居中;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>fish</title>
<style type="text/css">
.box1 {
background-color: #cbedee;
padding: 30px 0;
}
.box2 {
width: 750px;
height: 100px;
/* 设置margin: 0 auto是让box2垂直水平居中 */
margin: 0 auto;
background: linear-gradient(180deg, #ffce82, #ffa15a);
border-radius: 50px;
box-shadow: 0px 6px 10px 0px #d63d00, 0px 6px 0px 0px #ff7848,
0px 2px 0px 0px #ffffff inset;
/* box2中的文字 */
font-size: 36px;
font-weight: bold;
color: #fff;
text-shadow: 0px 2px 4px 0px #bd2e00;
/* 调节文字的水平垂直居中,方法一 */
/* text-align: center;
line-height: 100px; */
/* 调节文字的水平垂直居中,方法一 */
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">服务电话:400-123-456</div>
</div>
<script></script>
</body>
</html>