CSS3:如何使元素的:after和:before伪元素与元素高度对齐

3
我在头部设计方面遇到了一个大问题:
这里是演示:http://jsfiddle.net/uGECm/ 想法是有一个“包裹”元素的灰色标签;但是,标签的高度不确定(它可以因其内容而变化)-我的问题是,如果标签改变大小,由两个假伪元素制成的三角形位置会出错,因为它们的位置是相对的。
有什么想法吗?
注:我正在寻找无JS和无图像解决方案。

不错的使用CSS边框三角形。 - Matt Coughlin
@MattCoughlin 谢谢,我在这里看到了它们:http://css-tricks.com/snippets/css/css-triangle/ - Strae
3个回答

3
section h2:before, section h2:after {
    width: 0;
    height: 0;
    display: block;
    position: absolute;
    bottom: 0;
    margin: 0 0 -10px 0;
}

section h2:before {
    content: '\0000a0';
    border-left: 10px solid transparent;
    border-top: 10px solid #323232;
}

section h2:after {
    content: '\0000a0';
    border-right: 10px solid transparent;
    border-top: 10px solid #323232;
    right: 0;
}​

这是一个带有进一步CSS格式的分支:http://jsfiddle.net/bqXeJ/ 值得一看的是样式指南,例如我在这里写的样式指南,还有,如果您使用Lea Verou的prefixfree.js,则可以跳过为每个浏览器供应商编写声明。

很高兴能帮上忙。我还加了一些额外的信息,我认为也值得一看。 - Jezen Thomas

1

您可以将伪元素绝对定位。由于 section h2 元素的 position: relative,将它们设置为 top: 100% 将使它们固定在底部,无论父元素的大小如何:

section h2:before, section h2:after {
  position: absolute;
  top: 100%;
}

1
  • 对于:before和:after,使用绝对位置而不是相对位置
  • 同时应用bottom:-10px;
  • 分别应用left:0;right:0;
  • 移除浮动。对于绝对定位的元素,浮动没有任何效果。

已更新jsfiddle演示

section h2:before,
section h2:after {
    content: '\0000a0';
    width: 0;
    height: 0;
    position: absolute;    
    bottom: -10px;
    display: block;
}
section h2:before {
    border-left: 10px solid transparent;
    border-top: 10px solid #323232;
    left: 0;
}
section h2:after {
    border-right: 10px solid transparent;
    border-top: 10px solid #323232;
    right: 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接