:before,:after和padding

时间:2013-01-07 12:53:02

标签: css image hyperlink padding

我有以下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;
}

哪个样式的链接看起来像这样: enter image description here

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

2 个答案:

答案 0 :(得分:24)

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

View on JSFiddle

HTML

<div></div>

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;
}

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

以上代码的要点如下:

  1. 父母相对定位。这允许我们对其子元素(假元素)使用绝对定位,将它们放置在与父母相关的位置。
  2. 如果您希望元素是边界到边框,则前后元素的左右位置分别等于它们的宽度。
  3. 如果要将文本垂直居中于父div,并且它只是一行,则可以将行高设置为等于容器的高度。 View that here。如果那就是你想要的那样,这比“猜测”填充使其垂直居中更好。

    当然,还有其他方法可以垂直居中,因此有很多关于这个问题的SO问题。 Here's just one

答案 1 :(得分:0)

我刚刚根据rem值(例如, height: 2 rem。无法确认这是最好的解决方案,但是对于响应能力,只需一行代码即可完美解决。

相关问题