:before,:after和padding

Joh*_*ith 14 css image padding hyperlink

我有以下css代码:

.readMore:before {
    content: '';
    display: block;
    float: left;
    width: 10px;
    height: 27px;
    margin: 0;
    background: red url('images/button.png');
    background-position: 0 0;
}

.readMore {
    float: left;
    height: 24px;
    background: url('images/button.png');
    background-position: -10px 0;
    border: 0;
    margin: 0;
    padding: 4px 0 0 0;
    cursor: pointer: 
}

.readMore:after {
    content: '';
    display: block;
    float: right;
    width: 10px;
    height: 27px;
    margin: 0;
    top: -3px;
    background: red url('images/button.png');
    background-position: -411px 0;
}
Run Code Online (Sandbox Code Playgroud)

哪个样式的链接看起来像这样: 在此输入图像描述

但是当试图在垂直方向上调整.readMore中的文本时:before和:after图像也会"跳跃"下来.这是合乎逻辑的,但有没有解决方案,以便更好地与"总图像"对齐?

jam*_*ase 25

我倾向于使用absolute定位:before和:after元素.然后你可以做任何你想要的父母,而不用担心你的伪元素会去任何地方(当然,除非你移动元素本身).

在JSFiddle上查看

HTML

<div></div>
Run Code Online (Sandbox Code Playgroud)

CSS

div {
  position: relative;
  background: #eee;
  width: 25px;
  height: 25px;
  margin: 30px 0 0 30px;
}
div:before {
  position: absolute;
  width: 10px;
  height: 25px;
  top: 0;
  left: -10px;
  content:"";
  background: #222;
}
div:after {
  position: absolute;
  width: 10px;
  height: 25px;
  top: 0;
  right: -10px;
  content:"";
  background: #222;
}
Run Code Online (Sandbox Code Playgroud)

这显示了我如何将它们列出来.然后,您可以使用任何想要调整父文本中文本位置的方法.

以上代码的要点如下:

  1. 父母相对定位.这允许我们对其子元素伪元素使用绝对定位,将它们放置在与父元素相关的位置.
  2. 如果您希望元素是边界到边框,则前后元素的左右位置分别等于它们的宽度.

如果要将文本div垂直居中在父级中,并且它只是一行,则可以将行高设置为等于容器的高度.在这里查看.如果这就是你想要的,那么这将比"猜测"填充使其垂直居中更好.

当然,还有其他方法可以垂直居中,因此有很多关于这个主题的SO问题.这只是一个.