实现图标Icon+文字在div里自动中心居中(水平垂直居中)

已知div行高设置text-align:center文字会自动居中。

通过:before来设置icon的地址和高宽。

需要设置图片默认的垂直居中条件,与文字一致,为text-bottom。

设置图片行级显示。

<!Doctype html>
<html>
<head>
<style>
body{margin:0;padding:0;}
.con{position:absolute;500px;height:50px;border:1px red solid;
line-height:50px;color:green;text-align:center;
}
.txt{font-size:20px;}
.txt:before{
content:'111';
background-image:url('icon.png');
background-size:20px 20px;
vertical-align:text-bottom;
display:inline-block;
20px;
height:20px;
border:0;
top:0;
left:0;
}
</style>
</head>
<body>
<div class="con">
<span class="txt">我是三哥四哥五哥一个字</span>
</div>
</body>
</html>

实际效果,图标和文字会自动在div里中心居中

原文地址:https://www.cnblogs.com/heyach/p/6391321.html