按钮内水平对齐文本和 &:after 图像

Horizontal align text and &:after image inside button

我有下一个按钮:<button className="my-button">Deposit</button>

除了"Deposit"文字外,还应该有一张存款图片。我用 &:after 技巧添加它。看起来像:

问题:得到如下结果。当然,我可以将 deposit.png 对齐到正确的位置,但我无法移动按钮文本。

问题: 如何在没有额外包装的情况下对齐 Deposit 文本和 deposit.png 按钮内部(仅使用 css )?

我的css:

button.my-button {
  position: relative;
  width: 125px;
  height: 40px;
  background: none;
  border: 2px solid fade(white, 70);
  border-radius: 4px;
  font-family: Proxima Nova Soft semibold, sans-serif;
  font-size: 13px;
  color: white;
  &:after {
    position: absolute;
    content: "";
    display: block;
    width: 19px;
    height: 16px;
    border: none;
    background: url('../assets/images/deposit.png') no-repeat;
  }
}

我的解决方法:

尝试使用 flex-box,但似乎不适用于 buttons

我制作了一个 Fiddle 可以满足您的需求。您需要将 :after 元素设为 display: inline-block;,并且 而不是 将其设为 position: absolute;。使其成为 position: absolute; 会将其从 'flow'

中移除

.my-button:after {display: inline-block; /* you have given it display:block - which makes it fall in next line*/ }

body {
  background: #333
}
.my-button {
  position: relative;
  width: 125px;
  height: 40px;
  background: none;
  border: 2px solid #eee;
  border-radius: 4px;
  font-family: Proxima Nova Soft semibold, sans-serif;
  font-size: 13px;
  color: white;
}
.my-button:after {
  content: "";
  vertical-align:middle;
  display: inline-block;
  /* you have given it display:block - which makes it fall in next line*/
  width: 19px;
  height: 16px;
  border: none;
  background: url('https://cdn2.iconfinder.com/data/icons/ledicons/money_pound.png') left top no-repeat;
}
<button class="my-button">Deposit</button>

before 和 after 所做的只是在元素的 contents 之前或之后切换一个额外的元素,无论这些内容是其他 html 元素还是文本不是'没关系。

通过使您的图像 position: relative 没有 topbottomleftright 定义和一个简单的 display: inline-block 它会充当文本。

由于您使用了 :after 伪选择器,该元素显然位于文本之后,您现在需要做的就是 space 从文本中选择它,并可能将其垂直居中。

您可以使用 vertical-align: middle 使其垂直居中(因为此图像通过 display: inline-block 表示为文本)

之后您可以使用 margin-left space 元素,因为 inline-block 元素允许有边距。 (padding 也可以正常工作,但在这种情况下,边距是更好的选择)

当文本变长时,这也会导致您的图像移动(除非您设置特定的 width/height 当然会裁剪或环绕图像)。

在这种情况下 margin > padding 的原因是因为你在 between 节点之间而不是在 within 节点之间间隔内容(那是不管怎么说这个想法 - 把它看作是添加一个带有边距的白色space)

希望这对您有所帮助,如果您需要更多信息,请随时询问。

您可以使用您的代码并仅添加 3 行代码,显示不必是内联块。

button:after {
  right: 10px;
  top: 50%;
  margin-top: -8px;
}