如何对齐文本和 :before icon 垂直居中?

How to align text and :before icon vertically center?

我正在尝试使背景中的图标和文本垂直居中,但我想我做错了什么。文本前的点没有完全居中于背景。为什么会这样?

有更好的方法吗?抱歉,我是新手。

.status {
    display: inline;
}

.success {
    font-family: roboto;
    color: #27ae60;
    background: #e1e1e1;
    border-radius: 50px;
    padding: 0px 50px 0px 50px;
    font-size: 38px;
}

.success:before {
   font-family: FontAwesome; 
   content: "\f111"; 
   font-size: 10px;
   margin-right: 16px;
   color: #27ae60;
   vertical-align: middle;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet">

<div class="status success">Purchuased</div>

最好的方法是利用 flexbox:

CSS:

.status {
  display: inline-flex; // flex or inline-flex here
}

.success:before {
 font-family: FontAwesome; 
 content: "\f111"; 
 font-size: 10px;
 margin-right: 16px;
 color: #27ae60;
 align-self: center; // use this instead of vertical-align: middle;
}
.status {
    display: inline;
}

.success {
    font-family: roboto;
    color: #27ae60;
    background: #e1e1e1;
    border-radius: 50px;
    padding: 0px 50px 0px 50px;
    font-size: 38px;
}

.success:before {
   font-family: FontAwesome; 
   content: "\f111"; 
   font-size: 10px;
   margin-right: 16px;
   color: #27ae60;
   vertical-align: 10px;
}

您可以使用 flexbox 或网格使文本和图标完美居中。 下面是一个使用 flexbox 的例子。

.status {
    /* Added */
    display: flex;
    align-items: center;
}

.success {
    font-family: roboto;
    color: #27ae60;
    background: #e1e1e1;
    border-radius: 50px;
    padding: 0px 50px 0px 50px;
    font-size: 38px;
}

.success:before {
   font-family: FontAwesome; 
   content: "\f111"; 
   font-size: 10px;
   margin-right: 16px;
   color: #27ae60;
   /* vertical-align: middle; Removed */
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet">

<div class="status success">Purchuased</div>

如果它只有 1 行代码你可以简单地添加 center 标签使它们在中间对齐,inline-flex 然后 align-items center 垂直对齐让我知道这是什么你是说。

.status {
    display: inline-flex;
    align-items:center;
}

.success {
    font-family: roboto;
    color: #27ae60;
    background: #e1e1e1;
    border-radius: 50px;
    padding: 0px 50px 0px 50px;
    font-size: 38px;
    
}

.success:before {
   font-family: FontAwesome; 
   content: "\f111"; 
   font-size: 10px;
   margin-right: 16px;
   color: #27ae60;
   vertical-align: middle;
 
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet">

<center><div class="status success">Purchased</div></center>

这对我有用

.status {
    display: inline;
    position: relative;
}

.success {
    font-family: roboto;
    color: #27ae60;
    background: #e1e1e1;
    border-radius: 50px;
    padding: 0px 50px 0px 50px;
    font-size: 38px;
}

.success:before {
    position: absolute;
    font-family: FontAwesome;
    content: "\f111";
    font-size: 10px;
    margin-right: 16px;
    color: #27ae60;
    transform: translate(-25px, 21px);

}