在前端开发中除了实现div居中之外,还经常需要让字体水平垂直居中,div实现水平垂直居中可以参考使用flex布局和translate实现div水平和垂直居中,文字的水平和垂直居中代码实现如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.contain1{
width: 100%;
height: 100%;
}
.contain1 > div{
position: absolute;
width: 50%;
height: 50%;
}
.div2{
right: 0;
background: rgba(149,64,36,0.6);
/*开启flex布局*/
display: flex;
/*垂直居中*/
align-items: center;
/*水平居中*/
justify-content: center;
}
.div3{
top: 50%;
background: cyan;
display: flex;
align-items: center;
justify-content: center;
}
.div33{
width: 200px;
background: rgba(36,49,64,0.6);
/*height+line-height控制字体垂直居中
* text-align控制字体 水平居中*/
height: 200px;
line-height: 200px;
text-align: center;
}
</style>
</head>
<body>
<div id="contain1" class="contain1">
<div id="div2" class="div2">
我是居中字体
</div>
<div id="div3" class="div3">
<div id="div33" class="div33">我是居中字体</div>
</div>
</div>
</body>
</html>
效果如图: